我尝试在点击时切换背景颜色的动画(以及表单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);
});
});
});
答案 0 :(得分:1)
使用类来做到这一点......
在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");
答案 1 :(得分:1)
你使用的是什么jQuery版本?截至jQuery 1.8 {@ 3}}已被弃用,并且已移除1.9 .toggle()
。
因此,人们不会对与.toggle()
相关的toggle animation感到困惑。
注意:此方法签名在jQuery 1.8中已弃用并已删除 在jQuery 1.9中。 jQuery还提供了一个名为的动画方法 toggle event切换元素的可见性。是否 动画或触发的事件方法取决于参数集 过去了。
如果您使用的是1.9或更高版本,则可以尝试编写自己的切换功能。当然这种方法是基本的,可以建立在其上。
$.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 });
};
中查看
只需注意,您还可以使用jQueryUI为背景颜色设置动画。这是演示中使用的内容。
答案 2 :(得分:0)
根据此处的文档http://api.jquery.com/animate/,您无法为背景颜色设置动画。
来自文档
除非使用jQuery.Color()插件,否则background-color无法 - 动画 -
我没有使用它,但这里是他们提到的颜色插件。