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

标签 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;
}

最佳答案

这是一个 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 可能更好。

关于javascript - jQuery:动画完成后更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22312041/

相关文章:

Javascript - 将数字变量拆分为函数

javascript - 函数不验证输入

Javascript 和 Jquery 弹出窗口

javascript - 由于 dragover 事件中的 DOM 操作,HTML5 draggable 的 drop 事件不会间歇性触发

javascript - 如何设置 google Map.Place.AutoComplete 结果的样式?

jQuery Datatables 插件无法与 ASP.NET MVC 一起使用

javascript - 使用 HTML/CSS/JQuery 实现 WYSIWYG 报表生成器?

html - 溢出:隐藏不适用于完整的视口(viewport)部分

html - 如何在滚动条上淡出图像?

html - Bootstrap - ASP.NET 核心