<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)
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者