SoFunction
Updated on 2025-02-28

How to achieve buffering motion effect by js

This article describes the method of JS to achieve buffering motion effects. Share it for your reference. The specific analysis is as follows:

This example can achieve the effect of being fast at the beginning and then slowing down until it stops.

Key points:

var speed = ()/8;

The target point subtracts the current position of the element divided by 8, because the value of offsetleft is always getting larger, so the value of the speed is always getting smaller.

speed = speed>0?(speed):(speed);

Round upwards when the forward speed is, and downwards when the reverse speed is

Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>Untitled 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>
<!--
 = function(){
 var box = ("box");
 var btn = ("btn");
 var timer=null;
  = function(){
  startrun(300);
 }
 function startrun(target){
  clearInterval(timer);
  timer = setInterval(function(){
  var speed = ()/8;
  speed = speed>0?(speed):(speed);
  if( == target){
   clearInterval(timer);
  }else{
    = +speed+"px";
  }
  ('abc').innerHTML+=+','+speed+'<br>';
  },30);
 }
}
//-->
</script>
</head>
<body>
<input  type="submit" value="Move to the right">
<div >
</div>
<br>
<textarea  cols="50" rows="10" 
style="margin-top:130px"></textarea>
</body>
</html>

I hope this article will be helpful to everyone's JavaScript programming.