简单的setInterval应用

时间:2021-01-18 07:29:09
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1{
width:500px;
height: 500px;
margin-top: 20px;
}
</style>
<script>
window.onload=function(){
var aBtn=document.getElementsByTagName('input');
var arrUrl=['images/img1.jpeg','images/img2.jpeg','images/img3.jpg','images/img4.jpeg','images/img5.jpg']
var num=0;
var timer=null;
var oDiv=document.getElementById('div1');
aBtn[0].onclick=function(){
clearInterval(timer);
timer=setInterval(function(){
oDiv.style.background='url('+arrUrl[num]+')';
num++;
num%=arrUrl.length;
},800);
}
aBtn[1].onclick=function(){
clearInterval(timer);
}
}
</script>
</head>
<body>
<input type="button" value="换背景">
<input type="button" value="停">
<div id="div1">hello world</div>
</body>
</html>