jQuery Animate()和BackgroundColor

我正在尝试通过使用JQuery更改背景颜色来创建简单的脉冲效果。 但是,我无法将backgroundColor设置为动画。

function show_user(dnid) { /* dnid is HTML ID of a div. */ if (! $(dnid).is(':visible')) { $(dnid).show() } $('html, body').animate({scrollTop: $(dnid).offset().top}); $(dnid).animate({backgroundColor: "#db1a35"}, 1200); } 

奇怪的是,这个替代动画有效:

 $(dnid).animate({opacity: "toggle"}, 1200); 

但这根本不是我想要的。

此外,函数中的show()和滚动function正常工作。 这只是背景颜色动画。

上面的function由此链接调用Locate Me

有人可以帮助我设置背景颜色的动画吗?

=========

谢谢大家的帮助。 很多类似的答案。 这就是我最终的结果

在我的标题中

然后在我的show_user函数之后滚动动画。

 var bgcol = $(dnid).css('backgroundColor'); $(dnid).animate({backgroundColor: "#db1a35"}, 2000); $(dnid).animate({backgroundColor: bgcol}, 2000); 

这会产生一个相对快速的红色“脉冲”,吸引用户的眼睛。

再一次感谢你的帮助。

jQuery默认不能为颜色设置动画。 为了动画颜色,请使用官方的jQuery.Color插件。

除非如下所述,否则应将所有动画属性设置为单个数值。 大多数非数字属性无法使用基本jQueryfunction进行动画处理(例如,宽度,高度或左边可以设置动画,但背景颜色不能,除非使用jQuery.Color()插件)。

资源

jQuery支持任何数字 CSS属性之间的动画,不包括颜色。 但是,还有其他库可以使动画颜色成为可能。 一个这样的库是恰当命名的jQuery Color 。 它的自述页面显示了几个使用jQuery .animate()函数如何使用它在颜色之间进行动画处理的示例

使用CSS animation属性和keyframes

看到它在行动

HTML

 

CSS

 div { background-color: red; height: 200px; width: 200px; -webkit-animation: pulse 1s ease-in 0 infinite normal both; -moz-animation: pulse 1s ease-in 0 infinite normal both; -o-animation: pulse 1s ease-in 0 infinite normal both; animation: pulse 1s ease-in 0 infinite normal both; } @-webkit-keyframes pulse { 0% { background-color: red; } 65% { background-color: #7F0093; } 100% { background-color: blue; } } @-moz-keyframes pulse { 0% { background-color: red; } 65% { background-color: #7F0093; } 100% { background-color: blue; } } @-ms-keyframes pulse { 0% { background-color: red; } 65% { background-color: #7F0093; } 100% { background-color: blue; } } @-o-keyframes pulse { 0% { background-color: red; } 65% { background-color: #7F0093; } 100% { background-color: blue; } } @keyframes pulse { 0% { background-color: red; } 65% { background-color: #7F0093; } 100% { background-color: blue; } } 

你必须先将背景设置为从颜色,否则它第二次不会做任何事情。 你还拼错了css属性'background-color'并把它放在引号中,就像我没有:)

 $(dnid).css({'background-color': "#ffffff"}); $(dnid).animate({'background-color': "#db1a35"}, 1200); 

只需在jQuery脚本下面添加这个,就完成了: