(编辑:jimmy 日期: 2024/11/17 浏览:2)
本文实例为大家分享了js鼠标跟随效果展示的具体代码,供大家参考,具体内容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body,div{ margin:0; padding:0; } #box{ position:relative; margin:20px auto; width:300px; height:300px; background:#008000; } #mark{ position:absolute; top:0; left:0; width:100px; height:100px; background:red; } </style> </head> <body> <div id='box'> </div> <script> var box = document.getElementById('box'); box.onmouseover = function(e){ e = e || window.event; var mark = document.createElement('div'); mark.id = "mark"; this.appendChild(mark); mark.style.left = e.clientX - this.offsetLeft + 5 + "px"; mark.style.top = e.clientY - this.offsetTop + 5 + "px"; //阻止mark盒子的onmouseover事件的冒泡传播 mark.onmouseover = function(e){ e = e || window.event; e.stopPropagation "px"; mark.style.top = e.clientY - this.offsetTop + 5 + "px"; } } //依然有问题:鼠标快速移动,首先会到mark上,此时浏览器在计算mark的位置,计算完成,mark到达指定的位置,此时鼠标又重新回到box上,触发了box的mouseover,也触发了mark的mouseout,也会传播到box的mouseout上,会把mark先删除,然后在创建 box.onmouseout = function(e){ e = e || window.event; var mark = document.getElementById('mark'); if(mark){ this.removeChild(mark); } } //上面代码也可以通过将over和out事件分别改为enter和leave //onmouseenter和onmouseover都是鼠标滑上去的行为,但是onmouseenter浏览器默认阻止了它的冒泡传播(mark的onmouseenter行为触发,不会传播到box);而onmouseover是存在冒泡传播的,想要阻止的话需要手动阻止 </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。