Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

jquery - CSS Transition Not Firing

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.

Here's my JS and CSS:

JS (jQuery):

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

CSS (just mozilla for the minute):

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

Am I messing up here, or is the "all in one quick hit" not the way things should be done?

All help is really appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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');

Working here:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...