简单实现js鼠标跟随效果
程序员文章站
2022-04-09 23:13:27
本文实例为大家分享了js鼠标跟随效果展示的具体代码,供大家参考,具体内容如下
本文实例为大家分享了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 ? e.stoppropagation():e.cancelbubble = true; } mark.onmouseout = function(e){ e = e || window.event; e.stoppropagation ? e.stoppropagation():e.cancelbubble = true; } } //以下代码会出现一个问题,当鼠标移动过快的时候,鼠标会进入到mark这个盒子,会触发它的mouseover行为,由于事件的冒泡传播机制,导致box的mouseover会重新被触发,导致红色盒子一直在不断的创建 box.onmousemove = function(e){ e = e || window.event; var mark = document.getelementbyid('mark'); if(mark){ mark.style.left = e.clientx - this.offsetleft + 5 + "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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。