CSS3 Transition to highlight new elements created

2019-03-08 18:51发布

问题:

I want to use a CSS3 color transition to apply a highlight-fading color effect (yellow to transparent) to new elements appended to the markup using JQuery.

CSS

#content div {
    background-color:transparent;
    -moz-transition:background-color 2s;
    -webkit-transition:background-color 2s;
    -o-transition:background-color 2s;
    transition:background-color 2s;
}

#content div.new {
    background-color:yellow;
}

HTML

<div id="content"></div>
<a id="add-element" href="#">add new element</a>

JS

$('#add-element').click(function() {
    var newElement = $('<div class="new">new element</div>');
    $('#content').append(newElement);
    newElement.removeClass('new');
});

When I click the link, the new element is created. Its class is "new" (background color yellow) and it's appended to the HTML markup. I should be able to immediately remove the "new" class to trigger the background color transition to transparent (or whatever other color). I'm obviously doing it wrong, since the background color of the new element is immediately shown as transparent, with no transition effect. I know I can do this in JQuery UI, but I'd like to use CSS3 transitions.

jsfiddle here:

http://jsfiddle.net/paulaner/fvv5q/

回答1:

I was able to get this to work with css3 animation:

@-webkit-keyframes yellow-fade {   
   0% {background: yellow;}
   100% {background: none;}
}

@keyframes yellow-fade {
   0% {background: yellow;}
   100% {background: none;}
}

.highlight {
   -webkit-animation: yellow-fade 2s ease-in 1;
   animation: yellow-fade 2s ease-in 1;
}

Just apply the highlight class to new elements:

$('#add-element').click(function() {

    var newElement = $('<div class="highlight">new element</div>');

    $('#content').append(newElement);

});

I tested in IE 10, Chrome, Safari, and latest FF and it works there. Probably won't work in IE 9 and below...

http://jsfiddle.net/nprather/WKSrV/3/

I got this method from this book in Safari Books Online: http://my.safaribooksonline.com/9780132366847/ch05lev1sec2?link=f1184788-851e-4eb6-bb0b-61cb0fb7756d&cid=shareLink



回答2:

Your code is almost perfect. You just have to trigger something in order to make the transition work. This can be done by adding 1 line of code to your script.

$('#add-element').click(function() {
    var newElement = $('<div class="new">new element</div>');
    $('#content').append(newElement);
    // trigger on focus on newly created div
    newElement.focus();

    newElement.removeClass('new');
});

http://jsfiddle.net/UXfqd/



回答3:

It's an ugly hack, but it seems to work. I'm sure there's a better way.

$('#add-element').click(function() {
    var newElement = $('<div class="new">new element</div>');
    $('#content').append(newElement);
    setTimeout(function(){
        newElement.removeClass('new');
    },0);
});

http://jsfiddle.net/fvv5q/22/