我现在在使用 jQuery 时遇到了问题。我想要的是动画完成后更改背景颜色。我一直无法弄清楚如何让它发挥作用。我不明白没有控制台错误。
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
声明的。您可以通过使用更具体的选择器覆盖它来解决此问题:
#slider.red {
background:red;
}
初始选择器 #slider
的特异性为 100。
新选择器 #slider.red
的特异性略高,为 110。
除此之外,动画完成后背景确实没有改变。我建议添加 callback/complete function到动画..
$("#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/