Home > Web Front-end > JS Tutorial > Detailed introduction to uniform motion and variable speed (buffering) motion in JavaScript_Basic knowledge

Detailed introduction to uniform motion and variable speed (buffering) motion in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 17:48:30
Original
1446 people have browsed it

The movement of a div is actually the changing distance between it and the browser border. If the rate of change is constant, it is uniform motion; if the rate of change is not constant, it is variable speed motion. When the rate of change is proportional to the distance from the browser border, then it can be said that the div is doing buffering movement.
Actually, it is very simple, just use a timer to change the distance between the div and the browser border every once in a while.

For example, moving at a constant speed:

Enter the timer: (do it every 30ms)
if (whether the end point is reached)
{Stop timer}
else do{Change distance}

The method of changing distance determines whether to move at a constant speed or at a variable speed (buffering).

For example:

Copy the code The code is 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 The code is 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 );
};

In this way, a motion framework is written! The principle is simple, but it still needs to be perfected. Take your time!
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template