jQuery:动画完成后更改背景颜色

时间:2014-03-10 21:47:25

标签: javascript jquery html css

我现在遇到jQuery问题。我想要的是在动画完成后改变背景颜色。我无法弄清楚如何使它工作。我不明白没有控制台错误。

http://jsfiddle.net/4pmzf/

jQuery的:

$("#slider").toggle(function () {
    $(this).animate({
        "height":"100px"
    }, 1000).addClass('red');
}, function () {
    $(this).animate({
        "height":"20px"
    }, 1000).removeClass('red');
});

CSS

#slider {
    width: 100%;
    background: black;
    height: 20px;
    cursor: pointer;
}
.red {
    background: red;
}

1 个答案:

答案 0 :(得分:2)

这是specificity issue。初始背景声明具有更高的特异性,因为它是用id声明的。您可以通过使用更具体的选择器覆盖它来解决此问题:

UPDATED EXAMPLE HERE

#slider.red {
    background:red;
}

初始选择器#slider的特异性为100。

新选择器#slider.red的特异性略高于110。

除此之外,在动画完成后,背景确实没有被改变。我建议在动画中添加callback/complete function ..

CALLBACK EXAMPLE HERE

$("#slider").toggle(function () {
    $(this).animate({
        "height":"100px"
    }, 1000, function(){
        $(this).css('background','red');
    });
}, function () {
    $(this).animate({
        "height":"20px"
    }, 1000, function(){
        $(this).css('background','');
    });
});

另外..而不是改变类,最好只修改CSS。