Simple background switching
jquery part
$(function(){
function direct(){
for(var i=0;i<2;i++){
$(".bg_img").eq(i).show().siblings().hide();
}
}
setInterval(direct,1000);
})
html section
<p class="main_bg">
<p class="bg_img bg1"></p>
<p class="bg_img bg2"></p>
</p>
css part
.bg2 default display:none;
setInterval() has only been executed once, so I would like to ask why it cannot be entered a second time?
Dear bosses, please don’t despise me, thank you for your answers~
人生最曼妙的風景,竟是內心的淡定與從容!
Not to despise you, but this is obviously a syntax problem... In fact, I think setInterval is always executed, but the running result of your function direct
is fixed. The final result of the loop is that the second picture is displayed and the first picture is hidden. , so it looks like it's not executed.
You should do this:
var current = 0;
function direct(){
$(".bg_img").eq(current).show()
.siblings().hide();
current++;
if (current > 1) {
current = 0;
}
}
A closure is used here to save the state outside the timer so that it can be looped down each time.
In addition, add some knowledge about rendering. For this kind of for
loop to change the view state, the browser will cache these states and then render them at an appropriate time, instead of rendering them immediately as soon as you modify it. So you can't even see it flash.
Please refer to it
$(function(){
function direct(i){
$(".bg_img").eq(i).show().siblings().hide();
}
var i = 0;
setInterval(function () {
direct(i)
i = (i + 1) % $(".bg_img").length
}, 1000);
})
setInterval(function direct(){
for(var i=0;i<2;i++){
$(".bg_img").eq(i).show().siblings().hide();
}
},1000);
直接這樣試試,控制臺看看,有沒有報錯,如果報錯的話,js也不會繼續(xù)執(zhí)行了的。
After looping once, the value of i is 1 and then it remains 1. Try using let
Do you want this effect to be displayed one by one in order?
jQuery(function($){
var bgImg = $(".bg_img"),
maxIndex = bgImg.length - 1,
i = 0;
function direct(){
bgImg.eq(i).show().siblings().hide();
if (i < maxIndex) {
i++;
} else {
i = 0;
}
}
setInterval(direct, 1000);
});
$(function(){
var index = 0;
setInterval(function(){
(index < $('.bg_img').length) ? index ++ : index = 0;
$('.bg_img').eq(index).show().siblings().hide();
},1000);
})
setInterval(direct(),1000);
I don’t know if it’s right, but I always feel that this is the problem