JS实现提示框跟随鼠标移动

2022-10-16,,,

分享实例代码:

<!doctype html>
<html lang="en">
<head>

  <meta charset="utf-8">
  <title>title</title>
  <style>
    *{
      padding: 0;
      margin: 0;
    }
    .box{width:500px;margin: 300px auto;border: solid 1px black;position: relative;}
    .title{}
    .title h2{background-color: #ccc;padding: 10px 0; border: 1px solid #000;
      /*position: relative;*/
      /*z-index: 2;*/
      margin-bottom: 30px;}
    .cont p{width:200px;background: #eee;margin: 0;display: none;position: absolute;left: 0;top:0;
      /*z-index: 6;*/
     }

  </style>
</head>
<body>
<div class="box">
  <div class="title">
    <h2>二级标题二级标题二级标题1111</h2>
    <h2>二级标题二级标题二级标题2222</h2>
  </div>
  <div class="cont">
    <p>第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容第一个新闻内容</p>
    <p>第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容第二个新闻内容</p>
  </div>
</div>
</body>
<script>
var ah=document.queryselectorall(".title h2");
var ap=document.queryselectorall(".cont p");
  for(var i=0;i<ah.length;i++){//先遍历元素
    ah[i].index=i; //编号
    ah[i].onmouseover=function () {//移进来显示
      ap[this.index].style.display="block";

    }
    ah[i].onmouseout=function () {//移出去消失
      ap[this.index].style.display="none"
    }
    ah[i].onmousemove=function (eve) { //使p跟着鼠标走
      var e=eve||window.event
      ap[this.index].style.left=e.offsetx+5+"px";
     
      ap[this.index].style.top=e.offsety+5+
        this.offsettop+"px"; // 因为p的定位相对于大框,offset的坐标相对于事件源,不够,需要加上事件源相对于大框的left和top;+5是为了让p和h错开,这样p就不会一直闪烁了。
    }
  }
</script>
</html>

效果图片:

有兴趣的朋友们测试下,感谢大家对的支持。

《JS实现提示框跟随鼠标移动.doc》

下载本文的Word格式文档,以方便收藏与打印。