Home >Web Front-end >JS Tutorial >Analysis of implementation methods of uniform motion in javascript_javascript skills

Analysis of implementation methods of uniform motion in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:21:041251browse

The example in this article describes the implementation method of uniform motion in javascript. Share it with everyone for your reference, the details are as follows:

Steps of uniform motion:

1. Clear timer
2. Start the timer
3. Whether the exercise is completed: a. If the exercise is completed, clear the timer; b. Continue if the exercise is not completed

Condition for stopping uniform motion: the distance is close enough Math.abs (course distance - target distance) < Minimum motion distance

The screenshot of the running effect is as follows:

Uniform motion (simple motion) example of div:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript匀速运动</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 id="btn1">移动</button>
<div id="div1"></div>
<span></span>
</body>
</html>

For more content related to JavaScript motion effects, please view the special topic on this site: " Summary of JavaScript motion effects and techniques"

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn