SoFunction
Updated on 2025-02-28

js simple method to implement click left and right motion

This article describes the simple method of implementing click-to-left and left motion in js. Share it for your reference. The specific analysis is as follows:

Here you can realize the effect of clicking to the right, moving the square to the right, clicking to the left, and moving the square to the left.

You can use setInterval to achieve how long it takes and how long the div moves to achieve the motion effect.

Point 1: If the distance to the left of the element is less than the target distance, it is a positive movement, otherwise it is a negative movement

if( <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 velocity value.

if( ==target){
clearInterval(timer);
}
else{
 =  +speed +"px";
}

On the code

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

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