計時器的深入學習2(抖動原理)

1.抖動的實現原理:
a.通過獲取元素的位置left,用定時器改變left;
b.把一組數據(改變left的),比如16,-16,14,-14….0存到數組裏
c.然後開個計時器把數組裏的數字分別與原left值計算賦給left.最後數組走完的時候把計時器關閉

代碼如下:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<style type="text/css">
#div1{width:100px; height:100px; background-color:red; position:absolute; left:40px; top:40px;}
</style>
</head>
<body>
<input type="button" value="抖起來" id="btn"/>
<div id="div1"></div>
<script>
var arr=[]; 
for(var i=16;i>0;i-=2){
    arr.push(i,-i);
    } 
arr.push(0);
var onOff = true;
$('btn').onclick = function(){
    if(onOff){
        clearTimeout($('div1').timer2);
        var nowLeft = parseInt(getStyle($('div1'),'left'));
        var i = 0;
        clearInterval($('div1').timer1);
        $('div1').timer1 = setInterval(function(){
            doMove($('div1'),16,arr[i]+nowLeft,'left');
            if(i == arr.length-1){
                clearInterval($('div1').timer1);
            }else{
                i++;
            }
        },60)
    onOff = false;
    $('div1').timer2 = setTimeout(function(){
        onOff = true;
    },60*(arr.length+1))//此處代碼是爲了可以重複多次地實現點擊後出現抖動效果;“60*(arr.length+1))”是約束在完成一次抖動全過程之後,下一次抖動纔可發生;這可以避免因爲多次點擊從而引起位置錯亂的問題
    }

}
function $( v ){//$爲函數名
    if( typeof v === 'function' ){
        window.onload = v;
    } else if ( typeof v === 'string' ) {
        return document.getElementById(v);
    } else if ( typeof v === 'object' ) {
        return v;
    }
}
function getStyle( obj, attr ){
    return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle( obj )[attr];
}
function doMove(id,speed,where,howTo,endFn){
    speed = parseInt(getStyle( id, howTo ))> where ? -speed : speed;
    clearInterval(id.timer);
    id.timer=setInterval(function(){
        var nowLeft = parseInt(getStyle( id, howTo ));
        var thisLeft = nowLeft+ speed;
        if(thisLeft >=where&&speed>0||thisLeft <=where&&speed<0){
            thisLeft=where;
        }
        id.style[howTo] = thisLeft+'px';
        if(parseInt(getStyle( id, howTo ))===where){
            clearInterval(id.timer);
            endFn&&endFn();
        }
    },30)
}   
</script>
</body>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章