1.在开始运动时,关闭已有定时器
2.把运动和停止隔开(if/else)
demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#content {
width: 50px;
height: 50px;
background: red;
position: absolute;
left: 0px;
top:50px;
cursor: pointer;
}
#contentTwo{
width: 1px;
height: 350px;
background: black;
position: absolute;
left: 100px;
top:0px;
}
#contentThir{
width: 1px;
height: 350px;
background: black;
position: absolute;
left: 300px;
top:0px;
}
</style>
</head>
<body>
<input type="button" value="100" id="btn">
<input type="button" value="300" id="btn2">
<div id="content"></div>
<div id="contentTwo"></div>
<div id="contentThir"></div>
<script>
var cont=document.getElementById('content');
var btn=document.getElementById('btn');
var btn1=document.getElementById('btn2');
var timer;
btn.onclick=function(){
startMove(100);
}
btn1.onclick=function(){
startMove(300);
}
function startMove(target){
clearInterval(timer)
timer=setInterval(function(){
var speed=0;
if(cont.offsetLeft > target){
speed=-5;
}else{
speed=5;
}
if(Math.abs(target-cont.offsetLeft) <= 5){
clearInterval(timer);
cont.style.left=target + 'px';
}else{
cont.style.left=cont.offsetLeft + speed +'px';
}
},30)
}
</script>
</body>
</html>