js is a method for buffering the effect of movement

  • 2020-05-27 04:11:52
  • OfStack

This article illustrates an example of how js can buffer motion. Share with you for your reference. The specific analysis is as follows:

The example implements the effect of 1 starting quickly and then slowing down until it stops.

Key points:


var speed = (target-box.offsetLeft)/8;

The target point minus the value of the element's current position divided by 8, because offsetleft is 1 and it's getting bigger, so the velocity is also getting smaller


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

You round up the positive velocity, round down the negative velocity

Code:


<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title> Headless document </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=" Movement to the right ">
<div id="box">
</div>
<br>
<textarea id="abc" cols="50" rows="10" 
style="margin-top:130px"></textarea>
</body>
</html>

I hope this article is helpful for you to design javascript program.


Related articles: