CSS动画不会在jQuery中的addClass上触发 [英] CSS animation won't trigger on addClass in jQuery
问题描述
我有一个很奇怪的问题。我在jQuery中加载来自JSON的文章,当它们加载时,我想为每个动态元素添加一个'animate'类。
I have a very strange issue. I'm loading articles from JSON in jQuery and as they load, I'd like to add a class of 'animate' to each dynamic element.
$.each(jsonArticles, function (i, article) {
var $articleHTML = $(
'<article class="article">' +
'<a href="' + jsonObject.filmLink + article.reviewLink + '"><img src="' + jsonObject.imagePath + article.reviewImage + '" alt=""></a>' +
'<h1><a href="' + jsonObject.filmLink + article.reviewLink + '">' + article.reviewTitle + '</a></h1>' +
'<p><a href="' + jsonObject.filmLink + article.reviewLink + '">' + article.reviewSummary + '</a></p>' +
'</article>');
$articles
.append($articleHTML)
.find("article")
.addClass("animate");
});
所有这些都很好,并检查Firebug显示类已成功添加到每个文章标签。
All of this works great and checking in Firebug reveals that the class is successfully added to each article tag.
但是,当试图对添加的类使用CSS转换时,它不会动画,而是直接跳到最终样式(不透明度:1 )。
However, when trying to use a CSS transition on the article for the class that's added, it does not animate, but instead skips straight to the final style (opacity: 1).
.article {
opacity: 0;
-webkit-transition: all 0.5s ease;
-moz-transition: all 0.5s ease;
-o-transition: all 0.5s ease;
transition: all 0.5s ease;
}
.article.animate {
opacity: 1;
}
动画不会发生,并且文章成功设置为opacity:1.它立即显示。
The animation doesn't happen, but the class is added and the article is successfully set to opacity: 1. It shows up instantly.
任何人都有这个想法吗?
Anyone have any ideas about this? I cannot figure this one out at all.
另一点,这很有趣...如果我改变 .animate
类拥有:hover
,那么在我悬停和动画确实之前,文章将不会显示。为什么它会工作在悬停而不是当它只是立即添加,看起来很奇怪我。
On another point, which is rather interesting...if I change the .animate
class to have a :hover
, then the articles won't show until I hover and the animation does work. Why it would work for hover and not when it's simply added immediately, seems strange to me.
.article.animate:hover {
opacity: 1;
}
我会感谢任何输入。
感谢您,
Mikey。
Thanks, Mikey.
http://jsfiddle.net/Pz5CD/
请注意文章是如何弹出在100%不透明度。没有动画可见。
Live Demo: http://jsfiddle.net/Pz5CD/ Notice how the articles just pop in at 100% opacity. No animation is seen.
推荐答案
您需要在元素渲染到dom后添加类,set timout可能工作
You need to add the class to the element after it is rendered to the dom, a set timout might work
setTimeout(function(){
$articleHTML.addClass("animate");
}, i * 500 );
这篇关于CSS动画不会在jQuery中的addClass上触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!