问题描述
我想动画背景从彩色到透明。我有这样的代码:
I want to animate background from coloured to transparent. I have code like this:
$('.selector')
.animate({
'background-color' : 'transparent'
}, 2000, function () {
$(this).css({ 'background-color' : '' });
});
这很复杂,因为:
-
在动画完成后,我需要删除
style =
,否则style
将覆盖由
.hover
处理程序设置的CSS类。所以我使用了这个招数:
I need to remove the
style=""
after the animation finishes, because otherwise thestyle
would keep overriding the CSS class set by the.hover
handler. So I used this trick: jQuery - remove style added with .css() function
我不知道有什么更简洁的方法等待效果在jQuery中完成,请参阅:
I don't know of any neater way to wait for effects to complete in jQuery, see: How to wait for effect queue to complete in jQuery call sequence
那么,有没有更简单的解决方案?一些更聪明的使用jQuery效果,这不会那么复杂?
So, is there any simpler solution? Some more clever use of jQuery effects which wouldn't be so complicated?
我也试过了:
I also tried the trick with .animate(,1)
:
$('.selector')
.animate({
'background-color' : 'transparent'
}, 2000)
.animate({'background-color': ''}, 1);
但在这种情况下不起作用。
but it doesn't work in this case.
推荐答案
让CSS做动画,当不支持(例如)Modernizr时回退到javascript:
Let CSS do the animation, and fallback to javascript when it's not supported with (for example) Modernizr: http://modernizr.com/
if (Modernizr.csstransitions) {
// Animate background color
$('.element').addClass('animate-background-color');
} else {
// use javascript animation.
}
您的css:
.element {
-webkit-transition: background-color .5s ease-out 0.1s;
-moz-transition: background-color 5s ease-out 0.1s;
transition: background-color .5s ease-out 0.1s;
background-color: rgba(121,123,123,1);
}
.element.animate-background-color {
background-color: rgba(121,123,123,0);
}
css动画的小调:
Fiddle for the css animation: http://jsfiddle.net/c5PHf/
这篇关于jQuery动画到透明 - 更容易的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!