Home > Web Front-end > JS Tutorial > body text

How to implement div movement in javascript (code)

不言
Release: 2018-08-28 16:26:09
Original
5066 people have browsed it

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

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!

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