This article describes the basic framework of JS movement. Share it for your reference. The specific analysis is as follows:
Note here:
1. Turn off the existing timer when starting the movement
2. Separate movement from stop
Copy the code as follows: <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#div1{
width: 200px;
height: 200px;
background: red;
position: absolute;
left:0;
top:60px;
}
</style>
<script type="text/javascript">
window.onload=function(){
var oDiv=document.getElementById("div1");
var oBt=document.getElementsByTagName('input')[0];
var time=null;
oBt.onclick=function(){
clearInterval(time);//The first timer is to be turned off here, because this is to solve the bug where multiple buttons are clicked during the motion, resulting in multiple timers superimposed.
time=setInterval(function(){
var speed=7;
if(oDiv.offsetLeft<=600)
oDiv.style.left=oDiv.offsetLeft+speed+'px';
else{
clearInterval(time);
}
},30);
}
}
</script>
</head>
<body>
<input type="button" value="start movement" />
<div id="div1"></div>
</body>
</html>
I hope this article will be helpful to everyone's JavaScript programming.