JavaScript buffer motion implementation method of 2 is an example
- 2020-11-26 18:42:31
- OfStack
An example of JavaScript buffer motion is presented in this paper. To share for your reference, the details are as follows:
Principle of implementation :(target distance - current distance)/base = speed (the greater the distance moving, the smaller the speed; the distance moving is inversely proportional to the speed)
(500 - oDiv.offsetLeft) / 7 = iSpeed;
Note: when there is a decimal in the calculated speed, the whole should be taken;
(500 - oDiv.offsetLeft) / 7 = iSpeed; iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
Example 1: Slider buffering motion
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Buffer movement </title>
<style>
#div1{ width:100px; height:100px; background:red; position:absolute; top:50px; left:0;}
span{ width:1px; height:300px; background:black; position:absolute; left:300px; top:0; display:block;}
</style>
<script>
window.onload = function()
{
var oBtn = document.getElementById('btn1');
var oDiv = document.getElementById('div1');
oBtn.onclick = function()
{
startMove(oDiv, 300);
};
};
var timer = null;
function startMove(obj, iTarget)
{
clearInterval(timer);
timer = setInterval(function(){
var iSpeed = (iTarget - obj.offsetLeft)/8;
iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
if(iTarget==obj.offsetLeft){
clearInterval(timer);
}else{
obj.style.left = obj.offsetLeft + iSpeed + 'px';
}
}, 30);
}
</script>
</head>
<body>
<input id="btn1" type="button" value=" mobile " />
<div id="div1"></div>
<span></span>
</body>
</html>
Example 2: Sidebar swiping
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title> Slide the sidebar </title>
<style>
#div1{ width:100px; height:100px; background:red; position:absolute; right:0; top:0;}
</style>
<script>
window.onload = window.onscroll = function()
{
var oDiv = document.getElementById('div1');
var iScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var clientHeight = document.documentElement.clientHeight;
var iH = (clientHeight - oDiv.offsetHeight)/2 + iScrollTop;
//oDiv.style.top = iH + 'px';
startMove(oDiv, parseInt(iH));
};
var timer = null;
function startMove(obj, iTarget)
{
clearInterval(timer);
timer = setInterval(function(){
var iSpeed = (iTarget - obj.offsetTop) / 8;
iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
if(obj.offsetTop == iTarget){
clearInterval(timer);
}else{
obj.style.top = obj.offsetTop + iSpeed + 'px';
}
}, 30);
}
</script>
</head>
<body style="height:2000px;">
<div id="div1"></div>
</body>
</html>
For more information on the effects of JavaScript exercise, please visit our special topic: Summary of JavaScript Exercise Effects and Techniques.
I hope this article is helpful for JavaScript programming.