简单实现js鼠标跟随效果
作者:diasa
这篇文章主要教大家如何简单实现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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。