清除不了定时器。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="css/index.css"> </head> <body> <div class="wrapper"> <div class="header"> <span class="btn active">首页</span> <span class="btn">点击看看</span> <span class="btn">会自动的</span> <span class="btn">我的网址</span> </div> <div class="banner"> <img src="2.jpg" alt="`" class="active1"> <img src="3.jpg" alt="`"> <img src="4.jpg" alt="`"> <img src="5.jpg" alt="`"> </div> </div> <script src="js/index.js" ></script> </body> </html>
*{ padding: 0; margin: 0; } img{ width: 100%; } .wrapper{ width: 800px; height: 450px; margin: 150px auto; overflow: hidden; } .header{ width: 100%; height: 50px; text-align: center; border-radius: 5px; } .header .btn{ width: 200px; display: inline-block; height: 100%; float: left; line-height: 50px; color: #666; cursor: pointer; border-radius: 7px; } .active{ background-color: #ffcc00; } img{ display: none; } .banner .active1{ display: block; } .banner{ }
var index = 0, btn = document.getElementsByClassName('btn'), img = document.getElementsByTagName('img'), box = document.getElementsByClassName('wrapper')[0], timer = null; function startAutoPlay(){ timer = setInterval(function(){ index++; if(index>=btn.length) index=0; changeImg(); },1000) } function changeImg() { for (var i=0;i<btn.length;i++){ btn[i].className='btn'; img[i].className=''; } btn[index].className='btn active'; img[index].className='active1'; } startAutoPlay(); function stopAutoPlay(){ if(timer){ clearInterval(timer); } startAutoPlay(); } for(var i = 0;i<btn.length;i++){ btn[i].setAttribute("id",i); btn[i].addEventListener('click',function(){ index = this.getAttribute("id"); btn[index].className = "btn active"; stopAutoPlay(); changeImg(); }) } //鼠标划入box清除播放 box.addEventListener("mousemove",stopAutoPlay)
3
收起
正在回答 回答被采纳积分+1
2回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星