Timer application
SetInterval (function,1000) performs function once every 1000 milliseconds
SetTimeout (function,1000) performs function in 1000 milliseconds (performs one function)
Clearinterval () cleartimeout () off timer
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>move</title>
<style type= "Text/css" >
#c {
width:100px;
height:100px;
background-color:red;
Position:absolute;
}
</style>
<script type= "Text/javascript" >
var timer=null;
function Move () {
var Odiv=document.getelementbyid ("C");
Clearinterval (timer);
Timer=setinterval (function () {
var speed=5;
if (odiv.offsetleft>300) {
Clearinterval (timer);
}
else{
odiv.style.left=odiv.offsetleft+speed+ "px";
}
},30)
}
</script>
<body>
<input type= "button" value= "Start Motion" onclick= "Move ()" >
<div id= "C" ></div>
</body>
Skills:
Turn on the timer first, and then turn off the timer. If the timer is turned off in advance, the timer will be created again, and multiple timers work at the same time, accelerating the object movement.
Separate the movement from the stop. If you use only if, do not use else. The movement is performed again when the size is judged.
SetInterval (function () {left=offsetleft+speed;}, 30)
You should adjust the speed size when adjusting the velocity. when it gets bigger, it makes this movement "card".
div.style.left and div.style.offsetLeft differences
div.style.left Returns a string, such as 28px,div.style.offsetLeft Returns a value of 28, and offsetleft is convenient if the obtained value is to be calculated.
Style.left is read-write, and Offsetleft is readonly.
Offsetleft seems to have more character, haha.
Little tip for JavaScript motion.