问题
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 positionfixed
. - 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