CSS转换不触发 [英] CSS Transition Not Firing

查看:114
本文介绍了CSS转换不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个DOM元素(一个div),将其添加到DOM,然后在一个快速命中的javascript中更改其宽度。这理论上应该触发CSS3转换,但结果是从A到B,而没有之间的转换。

I'm creating a DOM element (a div), adding it to the DOM, then changing its width all in one quick hit in javascript. This in theory should trigger a CSS3 transition, but the result is straight from A to B, without the transition in between.

如果我通过单独的测试点击事件改变宽度,一切都会按预期的方式工作。

If I make the width change through a separate test click event everything works as expected.

和CSS:

JS(jQuery):

JS (jQuery):

var div = $('<div />').addClass('trans').css('width', '20px');
$('#container').append(div);
div.css('width', '200px');

CSS(只是mozilla分钟):

CSS (just mozilla for the minute):

.trans {
    -moz-transition-property: all;
    -moz-transition-duration: 5s;
    height: 20px;
    background-color: cyan;
}

我在这里搞砸了,

推荐答案

一个不依赖于setTimeout的更清洁的方法是在设置之前读取相关的css属性:

A cleaner approach that does not rely on setTimeout, is to read the css property in question before setting it:

var div = $('<div />').addClass('trans');
$('#container').append(div);
div.css('width');//add this line
div.css('width', '200px');

在这里工作:

http://jsfiddle.net/FYPpt/144/

如解释Lucero下面的注释,这样做是必要的,以强制浏览器计算一个实际值而不是自动,继承或类似的。没有实际值,浏览器将不会知道新值是从上一个更改。

As explained in the comments below by Lucero, doing it this way is necessary to force the browser to calculate an actual value rather than "auto", "inherit" or similar. Without an actual value, the browser will not know the new value to be a change from the previous.

这篇关于CSS转换不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆