Home > Web Front-end > JS Tutorial > js simple method to realize left and right click movement_javascript skills

js simple method to realize left and right click movement_javascript skills

WBOY
Release: 2016-05-16 16:05:04
Original
1287 people have browsed it

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;
}
Copy after login

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";
}
Copy after login

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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template