通过mousemove事件触发ClientX和ClientY时更新速度不够快。为什么?

时间:2018-10-23 15:18:34

标签: javascript addeventlistener mousemove

我有以下代码,希望跟随鼠标的div的轨迹会根据鼠标的移动方向而改变位置。似乎只有当我非常快速地移动鼠标时div的方向才会更新。

当我缓慢移动鼠标时,该事件仍会触发,但尾随div的位置不会相应改变。为什么会这样呢?这与我的代码有关,还是mousemove事件更新ClientX和ClientY属性的速度有问题?谢谢!

const body = document.querySelector('body');

let previousLeft = 0;
let previousTop = 0;
window.addEventListener('mousemove', function(e) {
  let leftMouse = e.clientX;
  let topMouse = e.clientY;
const mouseTrails = document.querySelectorAll('.mouseTrail');

  const setTrail = ((offsetX, offsetY) => {
    for (i = 0; i < mouseTrails.length; i++) {
      mouseTrails[i].style.left = leftMouse + "px";
      mouseTrails[i].style.top = topMouse + "px";
      mouseTrails[i].style.display = "block";

      leftMouse += offsetX;
      topMouse += offsetY;
    }
  });

  if (leftMouse > previousLeft && topMouse > previousTop) {
    setTrail(-20, -20);
  } else if (leftMouse < previousLeft && topMouse < previousTop) {
    setTrail(20, 20);
  } else if (leftMouse > previousLeft && topMouse < previousTop) {
    setTrail(-20, 20);
  } else if (leftMouse < previousLeft && topMouse > previousTop) {
    setTrail(20, -20);
  } else {
    setTrail(0, 0);
  }

  previousLeft = leftMouse;
  previousTop = topMouse;
});
.mouseTrail {
  height: 20px;
  width: 20px;
  background-color: tomato;
  transform: rotate(90deg);
  position: absolute;
  display: none;
}
<div class="mouseTrail"></div>
<div class="mouseTrail"></div>
<div class="mouseTrail"></div>
<div class="mouseTrail"></div>
<div class="mouseTrail"></div>

1 个答案:

答案 0 :(得分:0)

这可能与您使用的浏览器的速度有关。对我个人而言,该代码似乎可以正常工作。

您可以对代码进行一些优化,从而有可能加快其速度。

首先,您将在每次触发mousemove事件时查询DOM并创建一个新的“ setTrail”函数。您可以将这些移动到侦听器之外,以便鼠标移动时唯一执行的代码就是移动轨迹的代码。

const body = document.querySelector('body');

let previousLeft = 0;
let previousTop = 0;

const mouseTrails = document.querySelectorAll('.mouseTrail');

function setTrail(x, y, offsetX, offsetY) {
    for (i = 0; i < mouseTrails.length; i++){
        mouseTrails[i].style.left = x + "px";
        mouseTrails[i].style.top = y + "px";
        mouseTrails[i].style.display = "block";
        x += offsetX;
        y += offsetY;
    }
}

window.addEventListener('mousemove', function(e){
    let leftMouse = e.clientX;
    let topMouse = e.clientY;

    if(leftMouse > previousLeft && topMouse > previousTop){
         setTrail(leftMouse, topMouse, -20, -20);
    }
    else if(leftMouse < previousLeft && topMouse < previousTop){
         setTrail(leftMouse, topMouse, 20, 20);
    }
    else if(leftMouse > previousLeft && topMouse < previousTop){
         setTrail(leftMouse, topMouse, -20, 20);
    }
    else if(leftMouse < previousLeft && topMouse > previousTop){
         setTrail(leftMouse, topMouse, 20, -20);
    }        
    else{
         setTrail(leftMouse, topMouse, 0,0);
    }
    previousLeft = leftMouse;
    previousTop = topMouse;
});