webKit Transitions on Dynamic DOM Element
I my CSS file I define my div
class for 开发者_运维百科transitions:
div.BlackOut {
-webkit-transition-property: opacity;
-webkit-transition-duration: 2s;
}
Then, in my javascript add a dynamic dom element (via jQuery):
var cssObj = {
'background-color' : '#000',
'width' : '100%',
'height' : '400px',
'position' : 'absolute',
'top' : 0,
'z-index' : '9998'
};
var element = $("<div>").css(cssObj).addClass('BlackOut').appendTo( 'body' );
element.get(0).style.opacity = 0;
But the transition doesn't start!
Why?
I was running into the same problem, and found that my transformations would occur, but the transition would not run - no animation. It appears that if you try to execute the transitions before the element is in the DOM, it will ignore the transitions - while still executing the transformation. I don't know enough to say whether that's a bug or according to spec.
Anyway, if your new element is an image, you could add your transitions/css class via the load
event.
However, I was unable to find an event that fires when sans-url elements are added to the DOM. I chose to fall back on a timeout, which should work for you as well.
Your code would look something like this:
var element = $("<div id='BlackOutDiv'></div>").css(cssObj).appendTo( 'body' );
setTimeout(function() {
$('#BlackOutDiv').addClass('BlackOut');
}, 100);
I think you need an easing or perhaps an opacity
. So:
div.BlackOut {
opacity: 1;
-webkit-transition: opacity 2s ease-out;
}
That should work, but maybe you also would want to future proof your css, to also include other browsers (FF 4 for example):
div.BlackOut {
opacity: 1;
-webkit-transition: opacity 2s ease-out;
-khtml-transition: opacity 2s ease-out;
-moz-transition: opacity 2s ease-out;
-o-transition: opacity 2s ease-out;
transition: opacity 2s ease-out;
}
精彩评论