需求描述:当鼠标悬停在一个元素上的时候,显示气泡,气泡内容可以是一段文字或图片。实现如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>气泡显示</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <style type="text/css"> .container { margin-top: 130px; } #xsztip { padding: 8px 12px; width: 140px; display: block; font-size: 16px; color: #fff; font-weight: bold; background: #ED5517; cursor: pointer; } #xszimg { position: absolute; display: none; padding: 10px; width: 160px; background: #e0edf7; border-radius: 6px; } #xszimg::before { content: ""; position: relative; top: -20px; left: 10px; width: 0; height: 0; display: block; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid #e0edf7; } </style> </head> <body> <div class="container"> <span id="xsztip">鼠标悬停显示气泡</span> <div id="xszimg"> <span>这是需要提示的文字内容,可以修改!</span> </div> </div> <script type="text/javascript"> $(function(){ $("#xsztip").hover(function(){ show_xszimg(this); },function(){ show_xszimg(); }); function show_xszimg(f){ var d=$("#xszimg"); if(!f){ d.fadeOut() }else{ var c=$(f); var e=c.offset(); var a=e.left; var b=e.top + 44; d.css({left:a+"px",top:b+"px"}).show(); } } }); </script> </body> </html>