<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>运动</title>
</head>
<body>
<input type="button" value="运动" id="btn">
<div id="div1" style="width: 100px; height: 100px;background-color: #eee; position: absolute;"></div>
<script>
window.onload=function(){
var oDiv=document.getElementById('div1');
var oBtn=document.getElementById('btn');
var oTimer=null;
oBtn.onclick=function(){
clearInterval(oTimer); //开启定时器之前先关闭定时器,防止同时调用好几个定时器
oTimer=setInterval(function(){
if (oDiv.offsetLeft>=300) {
clearInterval(oTimer);
}else{
oDiv.style.left=oDiv.offsetLeft+5+'px'; //加if判断是因为当div已经到达300处时再点击div仍会动一下
}
},30)
}
}
</script>
</body>
</html>