Home>

Steps for uniform motion:

Clear timer

2. Start the timer

3. Whether the exercise is completed:a. The exercise is completed,Clear timerb. The exercise is not completed.

Conditions for stopping at a constant speed:the distance is close enough math.abs

The screenshot of the running effect is as follows:

Example of uniform motion (simple motion) of a div:

<! Doctype html>
<html>
<head>
<meta charset="utf-8">
<title>javascript uniform motion</title>
<style>
#div1 {width:100px;height:100px;background:red;position:absolute;top:50px;left:500px;}
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=0;
  if (obj.offsetleft<itarget)
  {
   ispeed=7;
  }
  else
  {
   ispeed=-7;
  }
  if (math.abs (obj.offsetleft-itarget)<7)
  {
   clearinterval (timer);
   obj.style.left=itarget + "px";
  }
  else
  {
   obj.style.left=obj.offsetleft + ispeed + "px";
  }
 }, 30);
}
</script>
</head>
<body>
<button>mobile</button>
<div></div>
<span></span>
</body>
</html>
  • Previous Android development art exploration study notes (7)
  • Next JavaScript buffer motion implementation method (2 examples)