Home > Article > Web Front-end > How to implement div movement in javascript (code)
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+'px'; //offsetLeft获取当前div的位置 },30); } } </script>
Related recommendations:
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!