1.效果很迷幻在点击之前如果不清除定时器对象的话!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" value="换背景"> <input type="button" value="停"> <script> window.onload = function () { var aImg = ['img/1.png','img/2.png','img/3.png','img/4.png']; //看到数据就要想到下标! var num = 0; var timer = null; var aBtn = document.getElementsByTagName('input'); var oBody = document.body; aBtn[0].onclick = function () { clearInterval(timer); //每次点击都会创建一个定时器对象,没有这句不断点击会出现迷幻的背景,根本停不下来。。。 timer = setInterval(changeBG,1000); } aBtn[1].onclick = function () { clearInterval(timer); } function changeBG() { oBody.style.background = 'url('+aImg[num] + ')'; num++; num %= aImg.length; } } </script> </body> </html>