jQuery背景颜色动画切换

我试图在点击时切换背景颜色的动画(以及表单slideToggle),但第一次点击隐藏元素(#opt4)而不是更改颜色。 我究竟做错了什么?

注意:当我运行单个背景动画时,而不是切换,它没有问题。 我想在用户再次点击链接时删除颜色。

$(document).ready(function() { $('#contact form').hide(); $('a#opt4').click(function(e) { e.preventDefault(); $('#contact form').slideToggle(); $(this).toggle(function() { $(this).animate({ backgroundColor: "#99ccff"},500); }, function() { $(this).animate({ backgroundColor: "none"},500); }); }); }); 

您使用的是什么jQuery版本? 截至jQuery 1.8 .toggle()已被弃用,并且1.9 .toggle()已被删除。

正因如此,人们不会对与切换事件相关的切换动画感到困惑。

注意:此方法签名在jQuery 1.8中已弃用,在jQuery 1.9中已删除。 jQuery还提供了一个名为.toggle()的动画方法,可以切换元素的可见性。 是否触发动画或事件方法取决于传递的参数集。

如果您使用的是1.9或更高版本,则可以尝试编写自己的切换function。 当然这种方法是基本的,可以建立在其上。

 $.fn.toggleState = function (even, odd) { this.toggled = this.data('toggled') || false; if (!toggled) { if (typeof even === 'function') { even(this); } } else { if (typeof odd === 'function') { odd(this); } } this.data({ toggled: !this.toggled }); }; 

哪个可以这样使用

 $('a#opt4').click(function (e) { e.preventDefault(); $(this).toggleState(function (el) { el.animate({ backgroundColor: "#99ccff" }, 500); }, function (el) { el.animate({ backgroundColor: "none" }, 500); }); }); $.fn.toggleState = function (even, odd) { this.toggled = this.data('toggled') || false; if (!this.toggled) { if (typeof even === 'function') { even(this); } } else { if (typeof odd === 'function') { odd(this); } } this.data({ toggled: !this.toggled }); }; 

在这个JSFiddle中查看它

只需注意,您还可以使用jQueryUI为背景颜色设置动画。 这是演示中使用的内容。

使用类来做到这一点……

在css中:

 .active-link{ background-color: #99ccff; -moz-transition: all 0.2s linear; -webkit-transition: all 0.2s linear; -o-transition: all 0.2s linear; transition: all 0.2s linear; } 

在你的JS中:

 $(this).toogleClass("active-link"); 

从http://api.jquery.com/animate/上的文档中,您无法为背景颜色设置动画。

来自文档

background-color无法 – 动画 – ,除非使用jQuery.Color()插件)

我没有用它,但这里是他们提到的颜色插件。

https://github.com/jquery/jquery-color/