js 匀速运动

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>运动</title>
<style>
#div1{
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 100px;
left: 0;
}
</style>
<script>
var time=null;
window.onload=function() {
var btn1=document.getElementById("btn1");
var div1=document.getElementById("div1")
btn1.onclick=function(){
clearInterval(time);
time=setInterval(function(){
var speed=10;
if(div1.offsetLeft>=300){
clearInterval(time);
}else{
div1.style.left=div1.offsetLeft+speed+"px";
}


}, 30)

}
}
</script>
</head>
<body>
<input type="button" id="btn1" value="开始运动">
<div id="div1"></div>
</body>
</html>

posted @ 2018-09-10 18:07  quitpoison  阅读(24)  评论(0)    收藏  举报