JS实现提示框跟随鼠标移动
在本篇内容里小编给各位整理了一篇关于JS实现提示框跟随鼠标移动的相关实例代码,需要的朋友们学习下。
.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
div
h2 二级标题二级标题二级标题1111 /h2
h2 二级标题二级标题二级标题2222 /h2
/div
div
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]. unction () {//移进来显示
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
效果图片:
有兴趣的朋友们测试下,感谢大家对凡科的支持。