Home  >  Article  >  Web Front-end  >  How to implement div movement in javascript (code)

How to implement div movement in javascript (code)

不言
不言Original
2018-08-28 16:26:095047browse

The content of this article is about how to implement div movement (code) in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Description: Click the button, the div moves, and specifies the stop position, (timer)

 <script>
      window.onload=function () {
          var timer=null;
          var btn1=document.getElementById("btn1");
          btn1.onclick=function () {
              var div1=document.getElementById("div1");
              clearInterval(timer);//如果多次点击,那么会有多个定时器同时工作,移动速度不是设置的10,会有叠加效果,故应该清除
             timer= setInterval(function () {
                 if(div1.offsetLeft>300)
                 {
                     clearInterval(timer);
                 }
                  else
                    div1.style.left=div1.offsetLeft+10+&#39;px&#39;;
                  //offsetLeft获取当前div的位置
              },30);
          }
      }
    </script>

Related recommendations:

Several different types of js Introduction to loop (with code)

How to implement user registration interface in javascript (with code)

The above is the detailed content of How to implement div movement in javascript (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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