我正在尝试在 Javascript 中重新启动一个
。我不想使用 transition
并且没有库或 cssSettimeout
或 clientHeight
之类的技巧来实现此目的。我知道这是因为回流,但我正试图为此找到理想的解决方案。
步骤如下:
1) Remove
transition -> 设置新位置(without
transition)
2) Add
transition -> 设置新位置(with
动画)
这是 Javascript。
let element1 = document.querySelector(".box")
document.querySelector("button").onclick = () => {
element1.style.transition = "none"
element1.style.transform = "translateY(50px)"
element1.style.transition = "all 0.4s";
element1.style.transform = "translateY(10px)"
}
现在只是进行过渡并移动 10px,而不是先设置 50px 的位置。
最佳答案
您的代码不起作用,因为浏览器不会重新计算您的第一批和第二批更新之间的样式。
一个技巧是通过调用其中一个函数来强制浏览器重新计算它们。例如,我将使用 getBoundingClientRect
,因为浏览器需要计算样式以获得元素的大小和位置。
所以:
let element1 = document.querySelector(".box")
document.querySelector("button").onclick = () => {
// Call the first batch of updates
element1.style.transition = "none";
element1.style.transform = "translateY(50px)";
// Force the browser recalculate the styles
element1.getBoundingClientRect();
// Call the second batch of updates
element1.style.transition = "all 0.4s";
element1.style.transform = "translateY(10px)";
}
关于javascript - 重启 css 过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45319754/