2 回答

TA贡献1803条经验 获得超3个赞
使用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>

TA贡献1831条经验 获得超9个赞
我怀疑您缺少的是元素必须具有绝对位置。这是一个有效的解决方案:
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>
添加回答
举报