<button id="btn">开始动画</button>
<button id="btn1">返回动画</button>
<div id="box" class="box"></div>
*{
margin: 0;
padding: 0;
border:none;
}
div{
width: 100px;
height: 100px;
background: red;
position: absolute;
}
window.onload = function(){
1.获取标签
var box = document.getElementById('box');
var btn = document.getElementById('btn');
var btn1 = document.getElementById('btn1');
2.点击按钮开始动画
btn.onclick = function(){
buffer(box,800);
}
btn1.onclick = function(){
buffer(box,0);
}
0.封装减速动画
(obj:表示进行动画的标签)
(target:表示目标值)
function buffer(obj,target){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
begin = box.offsetLeft;
三木运算符进行比较如果是正值就像上取整,反之向下。
var speed = target > begin ?Math.ceil((target - begin)*0.2):Math.floor((target - begin)*0.2);
obj.style.left = begin +speed +'px';
if (begin == target){
clearInterval(obj.timer);
}
},20)
}
}