The example in this article describes how to simply implement left and right click movements in js. Share it with everyone for your reference. The specific analysis is as follows:
Here you can achieve the effect of clicking to the right and the box moves to the right, clicking to the left and the box moving to the left
You can use setInterval to realize how long and how far the div should move to achieve the motion effect.
Point 1: If the left distance 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"; }
Upload 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>无标题文档</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="运动向右"> <input id="btn1" type="button" value="运动向左"> <div id="run"></div> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.