分享實例代碼:
<!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>
效果圖片:
有興趣的朋友們測試下,感謝大家對武林網的支持。
新聞熱點
疑難解答