简体   繁体   中英

CSS transitions for content loading

I'm implementing some animations on my HTML5 project with CSS3 and so far so good. I can do, for example:

#someDivId {
    position: absolute;
    background:rgba(255,0,0,0.75);
    transition: all 0.7s ease-in-out;
    -moz-transition: all 0.7s ease-in-out;
    -webkit-transition: all 0.7s ease-in-out;
    -o-transition: all 0.7s ease-in-out;
}   
#someDivId:hover {
    background:rgba(255,0,0,1);
}

And this will change the opacity of my red div from 0.75 to 1 . This work for other properties of the div on hover too, like the color attribute or even the border-radius .

My problem comes with attributes changed automatically when I manipulate the DOM with JavaScript , like the change in height or width that happens when an src is added to an img or if some content is added to a div .

For the image case, I have the folowing CSS:

.someImageClass {
    border-color: white;
    border-width: 15px;
    border-style: solid;
    max-height:370px;
    max-width:370px;
    transition: all 0.7s ease-in-out;
    -moz-transition: all 0.7s ease-in-out;
    -webkit-transition: all 0.7s ease-in-out;
    -o-transition: all 0.7s ease-in-out;
}

And the image is loaded to the DOM dynamically with JavaScript:

var image = document.createElement("img");
image.src = someSourceURL;
image.className = "someImageClass";
document.getElementById("someDiv").appendChild(image);

At first the image just appears as a square on the container DIV . When the img is not done loading it's content, it looks like this:

图片未加载

But when the content src is loaded, it looks like this:

图片已加载

I get no animations between the states.

There were at least two changes of size for the img that I identify, one from being nothing (no size, no style) and having its style applied (some size depending on style) and the second from being a node with no content but margin and size to one with its content loaded and a new size. I'm more concerned about the second one, and I'm not sure if the first one technically happens.

Is there a way to handle this kind of size changes triggered by manipulation of the content of a node just with CSS selectors and transitions?

You should add the CSS class name once the image is appended in side div.

You can achieve by using setTimeout function.

var image = document.createElement("img");
image.src = someImageClass;
document.getElementById("someDiv").appendChild(image);
setTimeout(function(){
    image.className = "someImageClass";
},1);

Or in Jquery

$('#someDiv').html('<img src="' + someImagePath + '" />');
setTimeout(function(){
    $('#someDiv img').addClass("someImageClass");
},1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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