下面的示例的问题在于,最后一个背景在setInterval
函数中未按计划显示6秒钟,而是立即消失为第一个背景。
当然,我希望它的行为与其余部分相同。 我认为它不会改变任何东西,但是我的实际示例使用的是背景图像而不是颜色,只是对本示例进行了更改,使其变得更加简单。
感谢您的帮助和时间!
var screen = 0,
speed = 1000;
window.setInterval(function() {
$(".background-" + ((screen % 4) + 1)).fadeOut(speed,
function() {
$(".background-" + (((screen + 1) % 4) + 1)).fadeIn(speed);
});
screen += 1
}, 6000);
.background-1 {
background: red;
z-index: 6;
position: absolute;
}
.background-2 {
background: blue;
z-index: 5;
position: absolute;
}
.background-3 {
background: green;
z-index: 4;
position: absolute;
}
.background-4 {
background: yellow;
z-index: 3;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="background background-1">
</div>
<div class="background background-2">
</div>
<div class="background background-3">
</div>
<div class="background background-4">
</div>
</div>
答案 0 :(得分:2)
var screen = 0,
speed = 1000;
window.setInterval(function() {
$(".background-" + ((screen % 4) + 1)).fadeOut(speed,
function() {
$(".background-" + (((screen + 1) % 4) + 1)).fadeIn(speed);
screen+=1
});
},6000);
.background-1 {
background: red;
z-index: 6;
position: absolute;
}
.background-2 {
background: blue;
z-index: 5;
position: absolute;
}
.background-3 {
background: green;
z-index: 4;
position: absolute;
}
.background-4 {
background: yellow;
z-index: 3;
position: absolute;
}
.wrapper{
width:400px;
}
.background {
width: 200px;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="wrapper">
<div class="background background-1">
</div>
<div class="background background-2">
</div>
<div class="background background-3">
</div>
<div class="background background-4">
</div>
</div>
在渐变的回调函数中设置变量screen
的增量。
答案 1 :(得分:2)
<script>
$(function () {
var speed = 1000;
var counter = 0
var divlist = $('.background-1, .background-2, .background-3,.background-4');
function showDiv() {
divlist.fadeOut(speed)
.filter(function (index) { return index == counter % 3; })
.fadeIn(speed);
counter++;
};
showDiv();
setInterval(function () {
showDiv();
}, 6000);
});
</script>
<div class="wrapper">
<div class="background background-1">
111111111111111111
</div>
<div class="background background-2">
22222222222222222222
</div>
<div class="background background-3">
33333333333333333333333333
</div>
<div class="background background-4">
4444444444444444444444444
</div>
</div>