我正在尝试编写一些 Vanilla Javascript 来使元素跟随我的鼠标移动。我使用了 clientX、clientY 和 mousemove 事件来使其跟随,但是当我滚动页面时,元素不会随鼠标移动。我想也许我需要使用滚动事件,但我正在努力使其工作。任何帮助都会很棒,谢谢!
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`;
})
- Use
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)