This time I will bring you a detailed explanation of the role of JS in implementing buffering motion. What are the precautions for JS to implement buffering motion? Here is a practical case, let’s take a look.
Buffering requires numerical rounding, rounding up: Math.ceil()
Rounding downMath.floor()
The effect of slowly slowing down the moving speed, moving speed = (end position - current position) / a number
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JS缓冲运动</title> <style> #p{ width:150px; height:150px; background:#0C6; position:absolute; left:0; top:50px; } #p2{ background:#000; height:600px; position:absolute; left:500px; width:2px; } </style> </head> <script> var speed; var time; window.onload = function(){ var btn = document.getElementById('btn'); btn.onclick = function(){ speed = 0; move(500); }; btn2.onclick = function(){ speed = 0; move(0); }; }; function move(e){ var p = document.getElementById('p'); clearInterval(time); time = setInterval(function(){ //改变位置,如果向左则e==500, 向上取整, 否则向右,向下取整,速度=(终点位置 - 当前位置)/一个数 e==500 ? speed = Math.ceil((e-(p.offsetLeft))/30):speed = Math.floor((e-(p.offsetLeft))/30) if (e <= p.style.left){//达到,关闭定时器 clearInterval(time); } else { p.style.left = p.offsetLeft+speed+'px'; } },30); }; </script> <body> <input type="button" value="向右运动" id="btn" /> <input type="button" value="向左运动" id="btn2" /> <p id = "p"> </p> <p id = "p2"> </p> </body> </html>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other php Chinese websites related articles!
Recommended reading:
Detailed explanation of the steps to implement full-screen scrolling plug-in in ES6
How to use the V-bind instruction in VueJs
The above is the detailed content of Detailed explanation of the role of buffering motion in JS. For more information, please follow other related articles on the PHP Chinese website!