js simple click left and right movement method

  • 2020-05-26 07:52:31
  • OfStack

The example of this article describes the simple implementation of js click left and right movement method. Share with you for your reference. The specific analysis is as follows:

Here you can click to the right, move the square to the right, click to the left, move the square to the left

You can use setInterval for too long, and div for how long you can move.

Point 1: if the distance to the left of the element is less than the target distance, it is moving in a positive direction, otherwise it is moving in a negative direction


if(run.offsetLeft <target){
speed = 2;
}else{
speed = -2;
}

Point 2: if the left distance of the element is equal to the target distance, stop the timer; otherwise, the left distance of the element is equal to the current left distance plus the speed value.


if(run.offsetLeft ==target){
clearInterval(timer);
}
else{
run.style.left = run.offsetLeft +speed +"px";
}

In the code


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title> Headless document </title>
<style>
body{margin:0; padding:0;}
#run{width:100px; height:100px; background:#06c;
position:absolute; border:1px solid #000;
left:0;}
</style>
<script>
window.onload = function(){
 var run = document.getElementById("run");
 var btn = document.getElementById("btn");
 var btn1 = document.getElementById("btn1");
 var speed = 2;
 var timer = null;
 btn.onclick = function(){
  startrun(300);
 }
 btn1.onclick = function(){
  startrun(0);
 }
 function startrun(target){
   clearInterval(timer);
  timer = setInterval(function(){
   if(run.offsetLeft <target){
    speed = 2;
   }else{
    speed = -2;
   }
   if(run.offsetLeft ==target){
    clearInterval(timer);
   }
   else{
    run.style.left = run.offsetLeft +speed +"px";
   }
  },30)
 }
}
</script>
</head>
<body>
<input id="btn" type="button" value=" Movement to the right ">
<input id="btn1" type="button" value=" Movement to the left ">
<div id="run"></div>
</body>
</html>

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


Related articles: