[英]jQuery Animate not working on background-color property
我正在使用jQuery .animate()
函数,并最终尝试根据用户滚动的像素数更改其中一个div
的background-color
。 令我惊讶的是,它没有用。 我尝试使用.css()
函数,它运行良好。 请参考底部的jsFiddle链接。
有人可以向我解释为什么会这样吗?
jsFiddle链接: https ://jsfiddle.net/ag_dhruv/cb2sypmu/
根据jQuery API文档 :
.animate()方法允许我们在任何数字CSS属性上创建动画效果。
动画属性和值
除非如下所述,否则应将所有动画属性设置为单个数值。 大多数非数字属性无法使用基本的jQuery功能进行动画处理(例如,
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; }
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <div class="toggler"> <div id="effect" class="ui-widget-content ui-corner-all"> <h3 class="ui-widget-header ui-corner-all">Animate</h3> <p> Etiam libero neque, luctus a, eleifend nec, semper at, lorem. Sed pede. Nulla lorem metus, adipiscing ut, luctus sed, hendrerit vitae, mi. </p> </div> </div> <button id="button" class="ui-state-default ui-corner-all">Toggle Effect</button>
jQuery UI捆绑了jQuery Color插件,它提供了颜色动画以及许多用于处理颜色的实用程序功能。
只是对现有答案的补充:如果你不想为此使用jQuery UI,你可以使用这个jQuery插件(仅限2.7kB):
http://www.bitstorm.org/jquery/color-animation/
您可以从项目的网站下载jquery.animate-colors.js
或jquery.animate-colors.min.js
,或者从CDN中包含它:
<script src="//cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
包含后,您可以通过以下方式使用颜色动画:
$('#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 changeBG(el,clr){
var elem = document.getElementById(el);
elem.style.transition = "background 1.0s linear 0s";
elem.style.background = clr;
}
链接到工作示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.