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:
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
setInterval(function direct(){
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?
$(function(){
})
I don’t know if it’s right, but I always feel that this is the problem