繁体   English   中英

jQuery背景颜色动画切换

[英]jQuery background colour animate toggle

我试图在单击时切换背景颜色的动画(以及表单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);
                    });

            });
        });

使用类来做到这一点...

在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");

您正在使用哪个jQuery版本? 从jQuery 1.8 .toggle() ,不推荐使用.toggle()而删除1.9 .toggle()

这样一来,人们就不会对切换事件所带来切换动画感到困惑。

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

如果您使用的是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设置背景颜色的动画。 演示中使用的是什么。

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

来自文档

除非使用jQuery.Color()插件,否则不能将background-color设置为动画-

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM