gpt4 book ai didi

javascript - jQuery 背景颜色动画切换

转载 作者:行者123 更新时间:2023-11-30 17:41:34 28 4
gpt4 key购买 nike

我试图在点击时切换背景颜色的动画(连同表单 slideToggle),但第一次点击隐藏元素 (a#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()已删除。

这样人们就不会对 toggle animation 感到困惑了相对于 toggle event .

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed.

如果您使用的是 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 });
};

在这个 JSFiddle 中查看

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

关于javascript - jQuery 背景颜色动画切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20980239/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com