html代码部分,将切换的图片设为main的背景图片
<div class="main" οnmοuseοver="stop()">
<img src="./img/logo.png" alt="" class="logo">
<nav>
<ul>
<li><a href="">Home</a></li>
<li><a href="">Mission</a></li>
<li><a href="">Whatawaitsyou</a></li>
<li><a href="">Portofile</a></li>
<li><a href="">Services</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
<img src="./img/red.png" alt="" class="red">
<ul class="three">
<li><a href=""><img src="./img/three.png" alt=""></a></li>
<li><a href=""><img src="./img/three.png" alt=""></a></li>
<li><a href=""><img src="./img/three.png" alt=""></a></li>
</ul>
</div>
js部分
count=1;
function timing(){
count = count++ === 4? 1:count;
document.getElementsByClassName("main")[0].style.backgroundImage="url(./img/"+count+".png)";
}
var clock=setInterval(timing,3000);
var star=function(){
clearInterval(clock);
clock=setInterval(timing,3000);
}
function stop () {
clearInterval(clock);
setTimeout(star,3000);
}
要注意的是clearInterval的参数是setinterval的id,不可以是函数,所以不能直接只用star()函数,要有一个状态然后clear clock状态,再用settimeout重新启动setinterval,
而在star函数里要先clear clock状态,不然就有两个setinterval 使切换加快,经测试,此方法无bug