匀速运动
程序员文章站
2024-03-16 20:50:28
...
js匀速运动
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 100px;
}
</style>
</head>
<body>
<button id="btn">move-></button>
<button id="btn_left">move<-</button>
<div class="box"></div>
<script>
// 单击按钮 让div匀速运动到500px停止
var btn = document.getElementById("btn");
var btn_left = document.getElementById("btn_left");
var oDiv = document.querySelector("div");
var timer=null;
var num=0;
btn.onclick=function(){
clearInterval(timer)
timer=setInterval(function(){
startMove(1000,5)
},20)
}
btn_left.onclick=function(){
clearInterval(timer)
timer=setInterval(function(){
startMove(0,-5)
},20)
}
function startMove(target,speed){
num+=speed;
if(oDiv.offsetLeft===target){
clearInterval(timer)
}else{
oDiv.style.left=num+"px";
}
}
</script>