效果如下图:
CSS部分
<style>
button {
margin: 5px;
border-radius: 2px;
}
.box {
position: relative;
left: 0px;
top: 0px;
height: 300px;
background: #eee;
}
.box1 {
position: absolute;
left: 0px;
top: 55px;
height: 75px;
width: 75px;
background-color: pink;
}
.box2 {
position: absolute;
left: 0px;
top: 195px;
height: 75px;
width: 75px;
background-color: blue;
}
</style>
body部分
<div class="box">
<button>200</button>
<button>400</button>
<div class="box1"></div>
<div class="box2"></div>
</div>
<script>
var btnArr = document.getElementsByTagName("button");
var box1 = document.getElementsByClassName("box1")[0];
var box2 = document.getElementsByClassName("box2")[0];
btnArr[0].onclick = function () {
animate(box1,200);
animate(box2,200);
}
btnArr[1].onclick = function () {
animate(box1,400);
animate(box2,400);
}
//形参ele是目标元素,形参target是目标距离
function animate(ele,target){
//创建定时器前,先把原来的定时器删掉
clearInterval(ele.timer);
var speed = target > ele.offsetLeft?10:-10;
//每一个元素绑定一个定时器,不容易混乱。
ele.timer = setInterval(function(){
//获取目标值与现实值之间的距离
var val = target - ele.offsetLeft;
ele.style.left = ele.offsetLeft + speed + "px";
//如果差值小于speed,直接设置left为target
if(Math.abs(val) < Math.abs(speed)){
//准备清除晃动
ele.style.left = target + "px";
clearInterval(ele.timer);
}
},30);
}
</script>