[英]animate background color multiple times.
I am trying to animate the background color of a div multiple times on different scrolltop value. 我试图在不同的scrolltop值上为div的背景色设置动画。 Below is the code I have, but it only changes the color once (it only listens to the second one.) can anyone help?
下面是我的代码,但是它只更改一次颜色(它仅侦听第二个颜色。)有人可以帮忙吗?
$(window).scroll(function() {
if($(window).scrollTop() >=200){
$('#div01').stop().animate({ backgroundColor: "#fff" },500);
}
else{
$('#div01').stop().animate({ backgroundColor: "#333" },500);
}
});
$(window).scroll(function() {
if($(window).scrollTop() >=500){
$('#div01').stop().animate({ backgroundColor: "#777" },500);
}
else{
$('#div01').stop().animate({ backgroundColor: "#fff" },500);
}
});
Give another condition for your first if
to check if $(window).scrollTop()
less than 500
: 给您的第一个条件,
if
要检查$(window).scrollTop()
小于500
:
if($(window).scrollTop() >=200 && $(window).scrollTop() < 500){
$('#div01').stop().animate({ backgroundColor: "#fff" },500);
}
else{
$('#div01').stop().animate({ backgroundColor: "#333" },500);
}
I have a feeling that your second $(window).scroll()
is overriding the first one. 我觉得您的第二个
$(window).scroll()
覆盖了第一个。 The following code should work. 下面的代码应该工作。
$(window).scroll(function() {
if($(window).scrollTop() >= 500){
$('#div01').stop().animate({ backgroundColor: "#777" },500);
}
else if($(window).scrollTop() >=200){
$('#div01').stop().animate({ backgroundColor: "#fff" },500);
}
else{
$('#div01').stop().animate({ backgroundColor: "#333" },500);
}
});
In any case, this is a more DRY version of your code. 无论如何,这是代码的DRY版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.