假设我有一个这样的风格,有一个过渡:
#theElement { position: relative; left: 200px; transition: left 1s; }
还有一些代码:
var element = document.getElementById("theElement"); function animateX(px) { element.style.left = px + "px"; }
所以,简单animateX
地说有一个函数,简单地说它的作用,动画左边的属性,theElement
现在如果我还想要一个立即设置左属性的函数,没有转换:
function setX(px) { element.style.transition = "none"; element.style.left = px + "px"; element.style.transition = "left 1s"; }
为什么这不起作用,我该如何解决?
为了使这项工作,您需要通过在JS中读取它们来刷新CSS更改.这个问题的答案解释了这是如何工作的:
我可以使用javascript强制浏览器"刷新"任何挂起的布局更改吗?
下面的工作示例:
var element = document.getElementById("theElement");
function animateX(px) {
element.style.left = px + "px";
}
function setX(px) {
element.style.transition = "none";
element.style.left = px + "px";
// apply the "transition: none" and "left: Xpx" rule immediately
flushCss(element);
// restore animation
element.style.transition = "";
}
function flushCss(element) {
// By reading the offsetHeight property, we are forcing
// the browser to flush the pending CSS changes (which it
// does to ensure the value obtained is accurate).
element.offsetHeight;
}
#theElement {
position: relative;
left: 200px;
transition: left 1s;
width: 50px;
height: 50px;
background: red;
}
.wrapper {
width: 400px;
height: 100px;
}