Uniform motion and variable speed (buffering) movement in javascript detail _ basics

Source: Internet
Author: User
Tags setinterval
The movement of a div is actually a change in its distance from the browser's border. If the rate of change is certain, it is uniform motion; if the rate of change is not necessarily, then it is variable motion. When the rate of change is proportional to the distance from the frame of the browser, then it can be said that Div is doing the buffer movement.
In fact, very simple, is to use a timer (timer), every once in a while to change the distance of the div-Poly browser border.

such as uniform motion:

Enter timer: (Every 30ms)
if (to reach the end)
{Stop Timer}
else do{Change Distance}

The way to change the distance is to decide whether it is uniform or variable speed (buffer) movement.

uniform, such as:
Copy Code code as follows:

var timer=null;
function Startmove ()
{

var Odiv=document.getelementbyid (' Div1 ');
Clearinterval (timer);
Timer=setinterval (function () {
var ispeed=1;

if (odiv.offsetleft>=300)
{
Clearinterval (timer);
}
Else
{
odiv.style.left=odiv.offsetleft+ispeed+ ' px ';
}
},30);
};


Buffer Movement:
Copy Code code as follows:


var timer=null;
function Startmove ()
{
var itarget=300;

var Odiv=document.getelementbyid (' Div1 ');

Clearinterval (timer);
Timer=setinterval (function () {
var ispeed= (Itarget-odiv.offsetleft)/8;

Ispeed=ispeed>0? Math.ceil (ispeed): Math.floor (Ispeed);

Ispeed=math.ceil (Ispeed);
if (odiv.offsetleft==itarget)
{
Clearinterval (timer);
}
Else
{
odiv.style.left=odiv.offsetleft+ispeed+ ' px ';
}
Document.title=odiv.style.left+ ' +ispeed;
},30);
};

So, a motion frame is written! The principle is simple, but still need to be perfected. Take it slow!
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.