跟随鼠标移动和滚动的元素

时间:2019-11-11 19:29:08

标签: javascript css mousemove

我正在尝试编写一些Vanilla Javascript,以使元素随鼠标移动而变化。我使用了clientX,clientY和mousemove事件来使其跟随,但是当我滚动页面时,该元素不会随着鼠标移动。我以为也许我需要使用scroll事件,但是我在努力使其工作。任何帮助都会很棒,谢谢!

document.addEventListener('mousemove', (e) => {
    const mouseFollow = document.getElementById('mouse-follow');
    const x = e.clientX - 25; //-25 to center div over mouse
    const y = e.clientY - 25; 

    mouseFollow.style.top = `${y}px`;
    mouseFollow.style.left = `${x}px`;
})

2 个答案:

答案 0 :(得分:1)

  • 使用position: fixed;clientX/Y相对于视口,CSS位置fixed相对。
  • 缓存您的选择器,无需每次鼠标移动就在DOM中查询元素

const mouseFollow = document.getElementById('mouse-follow');

document.addEventListener('mousemove', (e) => {
  mouseFollow.style.cssText = `
    left: ${e.clientX - 25}px;
    top:  ${e.clientY - 25}px;
  `;
});
body {
  height: 200vh;
}

#mouse-follow {
  position: fixed;
  left: 0;
  top:0;
  padding: 25px;
  background: red;
}
<div id="mouse-follow"></div>

答案 1 :(得分:1)

欢迎来到@ psshaw20。

我怀疑您缺少的是元素必须具有绝对位置。这是一个可行的解决方案:

document.addEventListener('mousemove', (e) => {

   const mouseFollow = document.getElementById('mouse-follow');
   const x = e.clientX - 25; //-25 to center div over mouse
   const y = e.clientY - 25; 
   console.log(x);
    
   mouseFollow.style.top = `${y}px`;
   mouseFollow.style.left = `${x}px`;
})
#mouse-follow{
  background: orange;
  position: absolute;
}
<span id=mouse-follow>*</span>

相关问题