Little tip for JavaScript motion.

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.