Home >Web Front-end >JS Tutorial >js method to achieve buffering motion effect_javascript skills
The example in this article describes the method of realizing buffering motion effect in js. Share it with everyone for your reference. The specific analysis is as follows:
This example can achieve the effect of starting very fast, then slowing down until it stops.
Key points:
var speed = (target-box.offsetLeft)/8;
The value of the target point minus the current position of the element is divided by 8. Because the value of offsetleft keeps getting bigger, the value of the speed keeps getting smaller
speed = speed>0?Math.ceil(speed):Math.floor(speed);
Forward speed is rounded up, and for reverse speed it is rounded down
Code:
<!DOCTYPE html> <html> <head> <meta charset="gb2312" /> <title>无标题文档</title> <style> <!-- body{margin:0; padding:0; font:12px/1.5 arial;} #box{width:100px; height:100px; position:absolute; background:#06c; left:0;} --> </style> <script> <!-- window.onload = function(){ var box = document.getElementById("box"); var btn = document.getElementById("btn"); var timer=null; btn.onclick = function(){ startrun(300); } function startrun(target){ clearInterval(timer); timer = setInterval(function(){ var speed = (target-box.offsetLeft)/8; speed = speed>0?Math.ceil(speed):Math.floor(speed); if(box.offsetLeft == target){ clearInterval(timer); }else{ box.style.left = box.offsetLeft+speed+"px"; } document.getElementById('abc').innerHTML+=box.offsetLeft+','+speed+'<br>'; },30); } } //--> </script> </head> <body> <input id="btn" type="submit" value="向右运动"> <div id="box"> </div> <br> <textarea id="abc" cols="50" rows="10" style="margin-top:130px"></textarea> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.