简单实现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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签: 鼠标 js