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


<!DOCTYPE html>
<meta charset="gb2312" />
<title> Headless document </title>
body{margin:0; padding:0; font:12px/1.5 arial;}
#box{width:100px; height:100px; position:absolute;
background:#06c; left:0;}
window.onload = function(){
 var box = document.getElementById("box");
 var btn = document.getElementById("btn");
 var timer=null;
 btn.onclick = function(){
 function startrun(target){
  timer = setInterval(function(){
  var speed = (target-box.offsetLeft)/8;
  speed = speed>0?Math.ceil(speed):Math.floor(speed);
  if(box.offsetLeft == target){
   box.style.left = box.offsetLeft+speed+"px";
<input id="btn" type="submit" value=" Movement to the right ">
<div id="box">
<textarea id="abc" cols="50" rows="10" 

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

Related articles: