Element following mouse movement and scroll

北慕城南 提交于 2021-01-21 10:31:53

问题


I'm trying to write a bit of Vanilla Javascript to make an element follow my mouse movements. I've used clientX, clientY and the mousemove event to make it follow, but when I scroll the page the element doesn't move with the mouse. I thought maybe I'd need to use the scroll event but I'm struggling to make it work. Any help would be great, thanks!

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`;
})

回答1:


  • Use position: fixed;. clientX/Y is relative to the viewport, so is CSS position fixed.
  • Cache your selector, there's no need to query the DOM for an element on every mouse move

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>



回答2:


Welcome to SO @psshaw20.

I suspect the thing you are missing is that the element must have an absolute position. Here is a working solution:

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>


来源:https://stackoverflow.com/questions/58807504/element-following-mouse-movement-and-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!