Home>

Implementation principle:(target distance-current distance)/radix=speed (the greater the movement distance, the lower the speed,Movement distance and speed are inversely proportional)

(500-odiv.offsetleft)/7=ispeed;

requires attention:When the calculated speed has a decimal, it needs to be rounded;

(500-odiv.offsetleft)/7=ispeed;ispeed=ispeed>0?math.ceil (ispeed):math.floor (ispeed);

Example 1:Slider buffers motion

<! Doctype html>
<html>
<head>
<meta charset="utf-8">
<title>buffer motion</title>
<style>
#div1 {width:100px;height:100px;background:red;position:absolute;top:50px;left:0;}
span {width:1px;height:300px;background:black;position:absolute;left:300px;top:0;display:block;}
</style>
<script>
window.onload=function ()
{
 var obtn=document.getelementbyid ("btn1");
 var odiv=document.getelementbyid ("div1");
 obtn.onclick=function ()
 {
  startmove (odiv, 300);
 };
};
var timer=null;
function startmove (obj, itarget)
{
 clearinterval (timer);
 timer=setinterval (function () {
  var ispeed=(itarget-obj.offsetleft)/8;
  ispeed=ispeed>0?math.ceil (ispeed):math.floor (ispeed);
  if (itarget == obj.offsetleft) {
   clearinterval (timer);
  } else {
   obj.style.left=obj.offsetleft + ispeed + "px";
  }
 }, 30);
}
</script>
</head>
<body>
<input type="button" value="mobile" />
<div></div>
<span></span>
</body>
</html>

Example 2:Sidebar sliding

<! Doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sidebar Slide</title>
<style>
#div1 {width:100px;height:100px;background:red;position:absolute;right:0;top:0;}
</style>
<script>
window.onload=window.onscroll=function ()
{
 var odiv=document.getelementbyid ("div1");
 var iscrolltop=document.documentelement.scrolltop || document.body.scrolltop;
 var clientheight=document.documentelement.clientheight;
 var ih=(clientheight-odiv.offsetheight)/2 + iscrolltop;
 //odiv.style.top=ih + "px";
 startmove (odiv, parseint (ih));
};
var timer=null;
function startmove (obj, itarget)
{
 clearinterval (timer);
 timer=setinterval (function () {
  var ispeed=(itarget-obj.offsettop)/8;
  ispeed=ispeed>0?math.ceil (ispeed):math.floor (ispeed);
  if (obj.offsettop == itarget) {
   clearinterval (timer);
  } else {
   obj.style.top=obj.offsettop + ispeed + "px";
  }
 }, 30);
}
</script>
</head>
<body>
<div></div>
</body>
</html>
  • Previous Analysis of the realization method of javascript uniform motion
  • Next Python master road python processing excel files (method summary)