简体   繁体   English

CSS过渡不适用于DOM操作

[英]CSS transition doesn't work on DOM manipulation

Let's say I've got some block with left style property defined and with transition for that property: 假设我有一些块,其中定义了left style属性,并对该属性进行了transition

<div id="caret" class="caret" style="left: 20px"></div>

.caret {
    transition: left 0.3s;
}

Okay, now when I change left via $.css() I've got everything transitioning perfectly: 好的,现在当我通过$.css() left时,一切都在完美过渡:

$('#caret').css('left', '100px');

But when I move the block from one place to another in DOM and then change left , nothing transitioning, it just immediately jumps to the given value: 但是,当我在DOM中将块从一个位置移动到另一个位置然后left更改时,没有任何过渡,它只是立即跳转到给定值:

$('#caret').appendTo('#container').css('left', '50px');

Hovever, if I wait a bit and change left again, transition is back again. 但是,如果我稍等一下再left ,过渡又回来了。 It feels like it needs some time to prepare. 感觉需要一些时间来准备。

I've created a simple showcase to demonstrate this issue: http://jsfiddle.net/L624m/2/ 我创建了一个简单的展示柜来演示此问题: http : //jsfiddle.net/L624m/2/

So, why is that happening? 那么,为什么会这样呢?

The problem is that your JavaScript code, in a typical browser, won't let the DOM create the new element first, so the style will actually be applied directly to the new element, causing no transition at all. 问题在于,在典型的浏览器中,您的JavaScript代码不会让DOM首先创建新元素,因此该样式实际上将直接应用于新元素,根本不会引起任何过渡。

After appending the element you have to "interrupt" the JavaScript and let the DOM notice the new element first; 追加元素后,您必须“中断” JavaScript,并让DOM首先注意到新元素。 usually this is done by using a setTimeout with 0ms interval, like: 通常,这是通过使用间隔为0ms的setTimeout完成的,例如:

setTimeout(function(){
    caret.css('left', left === '20px' ? '100px' : '20px');
},0);

So, because of the setTimeout , the browser will always queue the change in the left style after the changes in DOM are really made instead of being queued themselves too. 因此,由于setTimeout ,浏览器将始终在真正完成DOM更改后将 left样式的更改排队,而不是自己排队。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM