Use JS timer to make elements move

Use the JS timer to make an element as a method with a moving effect. The realization of the idea: first declare a variable to store the margin of the element from the left, and then we declare a variable to store the distance that the element needs to move each time, and then give this Just one completion time of the method. It should be noted that if the obtained value is not numeric data, it needs to be replaced, otherwise it cannot be judged. After judging that the element moves to a certain position, the step length gives it a negative value, and the element will run back.
You can also think about how to achieve the turning effect when the element moves to the left and right.

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title></title>
  <style type="text/css">
   *{
    
    margin: 0;padding: 0;}
   body{
    
    position: relative;}
   #box{
    
    
    width: 120px;height: 120px;background: green;
    position: absolute;top: 100px;
    /* 此处可以引入一个背景图作为移动的目标, */
    /* background: url(img/paobu_huaban.png) 0 0/100% 100%; */
   }
  </style>
 </head>
 <body>
  <button type="button" id="Button">点我移动</button>
  <div id="box" style="left: 0px;"></div>
  
  <script type="text/javascript">
   var Button = document.getElementById("Button");
   var box = document.getElementById("box");
   // 每次移动多少像素,step表示步长
   var step = 5;
   Button.onclick = function(){
    
    
    
    var timer = setInterval(function(){
    
    
     
     //获取box的left值,转成整数,一定要转化为数值行在做运算,
     // parseInt表示将获取到的字符串转化为字符型
     var o_left = parseInt(box.style.left);
     //想要元素走的更快可以改变加大每次移动的距离或者是减少完成时间也可以			  
    //但是减少完成时间这样的效果要好一点
     var n_left = o_left+step; //每次向右移动10px
     box.style.left = n_left+"px";
     if ( n_left>500) {
    
     //如果移动的距离大于400px就往回跑
      step = -5;
     }else if(n_left==0){
    
    
      step = 5;
     }; 
    },100);
   };
   
  </script>
 </body>
</html>

The results are as follows:
Running effect chart:

Guess you like

Origin blog.csdn.net/m0_46188681/article/details/105982416