javascript 不是每次都调用JS样式.setProperty

cvxl0en2  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(153)
嗨,这是我在stackoverflow上的第一个问题,所以请不要过分地拷问我:)

我有一个由mousemove上的eventListener调用的函数。该函数将鼠标坐标写入两个css变量。遗憾的是,由于某种原因,这并不会在每次调用该函数时更新

这是eventListener调用的函数
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>

https://gifyu.com/image/S7X4m
不知怎么的,我移动鼠标越快,它就越慢。有时候它就像半秒钟,直到css变量被更新。函数被明确地正确调用,console.log与鼠标移动一致。而且,没有控制台错误或类似的东西
为什么每次调用函数时不覆盖css变量?
先谢了!

yebdmbv4

yebdmbv41#

我没有足够的信誉来评论,但是你在哪里检查css变量是否更新了呢?
开发者工具只会更新这么频繁,所以即使css变量可能被正确更新,你也可能会看到延迟。

相关问题