在jQuery中是否可以动画化 background-color
,因为它目前无法正常工作。
$('#something').animate({
background :"red"
}, 1000);
在jQuery中是否可以动画化 background-color
,因为它目前无法正常工作。
$('#something').animate({
background :"red"
}, 1000);
因此,如果您使用jQuery UI,则可以动画化背景颜色。只需确保使用jQuery UI项目通过允许一些非数字样式(如颜色)进行动画化,扩展了
.animate()
方法。该项目还包括通过CSS类而不是单个属性指定动画的机制。
backgroundColor
而不是background
。试试这个:
$('#something').animate({ backgroundColor: "#FF0000" }, 1000, null, function () {
$('#something').css("backgroundColor", "#FF0000");
});
我在使用animate时遇到了不同的问题,但是发现使用它内置的回调函数再加上jQuery的css似乎适用于大多数情况。在IE9、FF4和Chrome中进行了测试,使用的是jQuery 1.5。
如果需要更完整的解决方案,请添加此插件:
$(document).ready(function () {
$.fn.animateHighlight = function (highlightColor, duration) {
var highlightBg = highlightColor || "#FF0000";
var animateMs = duration || 1000;
var originalBg = this.css("background-color");
if (!originalBg || originalBg == highlightBg)
originalBg = "#FFFFFF"; // default to white
jQuery(this)
.css("backgroundColor", highlightBg)
.animate({ backgroundColor: originalBg }, animateMs, null, function () {
jQuery(this).css("backgroundColor", originalBg);
});
};
});
并且可以这样调用:
$('#something').animateHighlight();
var start = [255, 0, 0], end=[255,255,255];
$('#element').animate({'aaa': 1}, {step: function(now){
$(this).css('background-color', 'rgb('+
parseInt(start[0] + (end[0]-start[0]) * now) + ',' +
parseInt(start[1] + (end[1]-start[1]) * now) + ',' +
parseInt(start[2] + (end[2]-start[2]) * now) + ')'
)
}, complete: function(){$(this).css('aaa', 0)}})
使用类似的语法(...{background-color :"red"}...
),我遇到了错误
SyntaxError: 意外的标记 -
通过将CSS属性background-color
封装在单引号中,我成功地让它工作:
$('#something').animate({
'background-color' :"red"
}, 1000);
您可以使用CSS3过渡来实现相同的效果。您的动画可以通过以下方式实现
#something {
-webkit-transition: background-color 1s linear;
transition: background-color 1s linear;
background: red;
}
edit
链接即可。 - Matt Ballbackground
是一种简写符号,用于定义background-color
、background-image
、background-position
、background-repeat
和background-attachment
。你试图动画化的属性(在你的问题中是固定的)是background-color
(或者在 JS 中不带引号的情况下是backgroundColor
)。 - David Thomas