jQuery Animate没有处理background-color属性
我正在使用jQuery .animate()
函数,并最终尝试根据用户滚动的像素数更改其中一个div
的background-color
。 令我惊讶的是,它没有用。 我尝试使用.css()
函数,它运行良好。 请参考底部的jsFiddle链接。
有人可以向我解释为什么会这样吗?
jsFiddle链接: https ://jsfiddle.net/ag_dhruv/cb2sypmu/
根据jQuery API文档 :
.animate()方法允许我们在任何数字CSS属性上创建动画效果。
动画属性和值
除非如下所述,否则应将所有动画属性设置为单个数值。 大多数非数字属性无法使用基本的jQueryfunction进行动画处理(例如,
width
,height
或left
可以设置动画, 但background-color
不能 ,除非使用jQuery.Color插件)
重点是我的
背景颜色不是数字属性,因此无法使用.animate()
进行动画.animate()
。
如果要为background-color
属性animate
,则需要包含jQueryUI
或添加此插件:
$(function() { var state = true; $("#button").click(function() { if (state) { $("#effect").animate({ backgroundColor: "#aa0000", color: "#fff", width: 500 }, 1000); } else { $("#effect").animate({ backgroundColor: "#fff", color: "#000", width: 240 }, 1000); } state = !state; }); });
.toggler { width: 500px; height: 200px; position: relative; } #button { padding: .5em 1em; text-decoration: none; } #effect { width: 240px; height: 135px; padding: 0.4em; position: relative; background: #fff; } #effect h3 { margin: 0; padding: 0.4em; text-align: center; }
只是对现有答案的补充:如果你不想为此使用jQuery UI,你可以使用这个jQuery插件(仅2.7kB):
http://www.bitstorm.org/jquery/color-animation/
您可以从项目的网站下载jquery.animate-colors.js
或jquery.animate-colors.min.js
,或者从CDN中包含它:
包含后,您可以通过以下方式使用颜色动画:
$('#demodiv').animate({color: '#E4D8B8'}) $('#demodiv').animate({backgroundColor: '#400101'}) $('#demodiv').animate({borderBottomColor: '#00346B'}) $('#demodiv').animate({borderColor: 'darkolivegreen'}) $('#demodiv').animate({color: 'rgba(42, 47, 76, 0.1)'})
您只能使用jQueryUI为backgroundColor设置动画。 如果您不想使用jQueryUI,则需要更改一个类,并使用转换在CSS中创建动画。
您也可以使用jQuery为背景颜色设置动画,而不是使用animate()方法,正如您所注意到的那样,css方法将会这样做。
因为这是一件非常简单的事情,所以不要在代码中包含另一个库,为自己节省http请求,并使用普通JS。
这个function会很好:
function changeBG(el,clr){ var elem = document.getElementById(el); elem.style.transition = "background 1.0s linear 0s"; elem.style.background = clr; }
链接到工作示例