mousemove事件中style.setProperty未实时更新,鼠标移动越快越卡顿
问题:鼠标移动时CSS变量无法实时更新?
您好,这是我第一次在Stack Overflow上提问,请手下留情 :)
我编写了一个通过mousemove事件监听器调用的函数,用于将鼠标坐标写入两个CSS变量,但不知为何该函数每次调用时CSS变量并未实时更新。
以下是事件监听器调用的函数代码:
var textMoved = false; var initialCoordinates = {x: 0, y: 0}; var documentRoot = document.querySelector(":root"); // ... document.addEventListener("mousemove", animateType) function animateType(e) { //check if its the first time the mouse is moving if (!textMoved) { // if yes, set the initial coordinates textMoved = true; initialCoordinates = { x: (e.clientX / window.innerWidth) * 100, y: (e.clientY / window.innerHeight) * 100, }; console.log("initial coordinates", initialCoordinates) } else { // if not, calculate a offset from the initial coordinates so the text doesn't flick when the mouse is moved the first time const {clientX, clientY} = e; const x = initialCoordinates.x - (clientX / window.innerWidth) * 100; const y = initialCoordinates.y - (clientY / window.innerHeight) * 100; documentRoot.style.setProperty("--entry-offset-1", x + "px"); documentRoot.style.setProperty("--entry-offset-2", y + "px"); console.log("offset", x, y); } }
div { background-color: red; height: 20px; width: 20px; position: absolute; transform: translate(var(--entry-offset-1), var(--entry-offset-2)); } body { padding: 150px; }
<div> </div>
奇怪的是,鼠标移动速度越快,卡顿越严重,有时CSS变量要半秒才更新。函数确实被正确调用,控制台日志与鼠标移动同步,且无任何报错。
为何CSS变量无法在函数每次调用时被覆盖更新?
提前感谢各位的解答!
内容的提问来源于stack exchange,提问作者stepframe
相关产品推荐
相关产品推荐

