A code instance _javascript technique for realizing uniform motion in JS

Source: Internet
Author: User

Effect:

Ideas:

Use the Setinerval () timer for movement. Then the key point is to give it a fill gap when the final stop is judged.

Code:

Copy Code code as follows:

<title></title>
<style type= "Text/css" >
#div1
{
width:100px;
height:100px;
Background: #0000FF;
Position:absolute;
left:800px;
top:100px;
}
#div200
{
width:1px;
height:400px;
Background: #FF0000;
Position:absolute;
left:200px;
}
#div500
{
width:1px;
height:400px;
Background: #FF0000;
Position:absolute;
left:500px;
}
</style>
<script type= "Text/javascript" >
function Move (end) {
var odiv = document.getElementById (' Div1 ');
var timer = null;
Timer = setinterval (function () {
var speed = (end-odiv.offsetleft)/5; Take out the speed of motion according to the endpoint and offsetleft
Speed = speed > 0?       Math.ceil (Speed): Math.floor (speed); Carry rounding, and decimal places become whole,
if (odiv.offsetleft <= end) {
Clearinterval (timer);
//                }
else {
ODiv.style.left = odiv.offsetleft + speed + ' px ';
//                }
if (Math.Abs (end-odiv.offsetleft) <= speed) {//due to a small gap at the end of the stop, or no complete arrival at the specified location, it is less than its speed
Clearinterval (timer); Let the timer stop when the distance is less than the speed
ODiv.style.left = end + ' px '; Fill the gap after stopping.
}
else {
ODiv.style.left = odiv.offsetleft + speed + ' px '; Move Div
}
}, 30)
}
</script>
<body>
<input type= "button" id= "Btn1" value= "to 500 position" onclick= "move (+);"/>
<input type= "button" id= "Btn2" value= "to 200 position" onclick= "move (MB);"/>
<div id= "Div1" >
</div>
<div id= "div200" >200
</div>
<div id= "div500" >500
</div>
</body>

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.