假设我有一个这样的风格,有一个过渡:
#theElement { position: relative; left: 200px; transition: left 1s; }
还有一些代码:
var element = document.getElementById("theElement"); function animateX(px) { element.style.left = px + "px"; }
所以,简单地说有一个animateX函数,简单地说它的作用,动画元素的左侧属性,现在如果我还想拥有一个立即设置左属性的函数,而不进行转换:
function setX(px) { element.style.transition = "none"; element.style.left = px + "px"; element.style.transition = "left 1s"; }
为什么这不起作用,我该如何解决?
解决方法
为了使这项工作,您需要通过在JS中读取它们来刷新CSS更改.这个问题的答案解释了这是如何工作的:
Can I use javascript to force the browser to “flush” any pending layout changes?
下面的工作示例:
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; }
<div class="wrapper"> <div id="theElement"></div> </div> <button onclick="animateX(100)">Animate 100</button> <button onclick="setX(0)">Set 0</button>