强制浏览器在更改CSS时触发回流 [英] Force browser to trigger reflow while changing CSS
问题描述
我正在构建基于CSS3过渡的非jQuery响应的图像滑块。
结构很简单:一个视口和内部相对定位的UL带有左浮动的LI。 / p>
我在这种情况下面临一个问题:
- 现在,UL已将CSS转换设置为
none 0s线性
以防止动画更改。在这一刻,我通过滑块宽度(让我们说:从0px到-1200px)减少UL CSS左值,使视图与它是一样的。 - 现在我改变UL的过渡属性
all 0.2s ease-out
。 - 现在我改变UL的left属性来触发CSS3动画。 (让我们说:从-1200像素到0像素)。
有什么问题?浏览器简化了更改,不会创建任何动画。
Stoyan Stefanov在他的博客中写道了回流问题在这里,但在这种情况下试图强制元素的回流不起作用。
(我为了简化跳过了浏览器前缀):
ul.style.transition ='none 0s linear 0s';
ul.style.left ='-600px';
ul.style.transition ='all 0.2s ease-out';
ul.style.left ='0px';
这里是无法看到问题的行动: http://jsfiddle.net/9WX5b/1/
感谢。
请求 offsetHeight
的元素做的一切都很好。您可以使用此函数强制回流,并传递样式已更改的元素:
函数回流
console.log(elt.offsetHeight);
}
请参见以下示例: http://jsfiddle.net/9WX5b/2/
I am building non-jQuery responsive image slider based on CSS3 transitions.
The structure is simple: a viewport and inside relatively positioned UL with left floated LIs.
I am facing a problem in such situation:
- User clicks "prev" arrow.
- JS appends proper LI before currently displayed LI node.
- For now UL has set CSS transition as
none 0s linear
to prevent animation changes. In this moment I decrease UL CSS left value by slider width (let's say: from 0px to -1200px) to make view the same as it was. - Now I am changing UL's transition property to
all 0.2s ease-out
. - Now I am changing UL's left property to trigger CSS3 animation. (let's say: from -1200px to 0px).
What is the problem? Browser simplifies changes and does not make any animations.
Stoyan Stefanov wrote about reflow problem at his blog here, but in this case trying to force a reflow on element doesn't work.
This is a piece of code doing this (I skipped browser prefixes for simplification):
ul.style.transition = 'none 0s linear 0s';
ul.style.left = '-600px';
ul.style.transition = 'all 0.2s ease-out';
ul.style.left = '0px';
Here is fiddle to see problem in action: http://jsfiddle.net/9WX5b/1/
Thanks.
Requesting the offsetHeight
of an element does everything nicely. You can force a reflow using this function and passing it the element that styles have been changed on:
function reflow(elt){
console.log(elt.offsetHeight);
}
And call this where reflows are needed. See this example: http://jsfiddle.net/9WX5b/2/
这篇关于强制浏览器在更改CSS时触发回流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!