一.doMove函数封装 抖原理 透明度封装

2017-07-10  本文已影响0人  2点半

doMove()

window.onload=function(){ 
    var oBtn1 = document.getElementById("btn1");
    var oDiv = document.getElementById("div1");
   oBtn1.onclick=function(){
       doMove(oDiv,'top',5,400,function(){
           doMove(oDiv,'left',3,800);
       });
   }
    oDiv.timer=null;
    function doMove(obj,attr,dir,target,endFn){
            dir=parseInt(getStyle(obj,attr))<target?dir:-dir;
            clearInterval(obj.timer);
            obj.timer=setInterval(function(){
                var speed=parseInt(getStyle(obj,attr))+dir;//步长
                if(speed>target && dir>0 || speed<target && dir<0) {speed=target}
                obj.style[attr]=speed+"px";
                if(speed==target) {
                    clearInterval(obj.timer);
                    endFn&&endFn();
                }

            },10);
    }
    function getStyle(obj,attr){return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr];}
}

<small>

抖动原理及实现过程

window.onload=function(){
    var oImg=document.getElementById('img1');
    oImg.onclick=function(){
            var pos=parseInt(getStyle(oImg,'left'));
            var arr=[];
            var timer=null;
            var num=0;
            for(var i=20;i>0;i-=5){
                arr.push(i,-i);
            }
            arr.push(0);
           clearInterval(timer);
           timer=setInterval(function(){
               oImg.style.left=pos+arr[num]+"px";
               num++;
               if(num==arr.length){
                   clearInterval(timer)
               }
           },50);
    }
}

<small>


抖的函数封装

shake(oImg,'top');
function shake(obj,attr,endFn){
    var pos=parseInt(getStyle(obj,attr));
    var arr=[];
    var num=0;
    for(var i=20;i>0;i-=5){arr.push(i,-i);  }
    arr.push(0);
    clearInterval(obj.time);
    obj.time=setInterval(function(){
        obj.style[attr]=pos+arr[num]+"px";
        num++;
        if(num==arr.length){
            clearInterval(obj.time);
            endFn&&endFn();
        }
    },50);
}

透明度的封装

function opacity(obj, num, target, endFn) {
    
        num = getStyle(obj, 'opacity')*100 < target ? num : -num;
        
        clearInterval( obj.opacity );
        
        obj.opacity = setInterval(function () {
            
            var speed = parseInt(getStyle(obj, 'opacity')*100) + num;
            
            if ( speed > target && num > 0 || speed < target && num < 0 ) {
                speed = target;
            }
            
            obj.style.opacity = speed/100;
            obj.style.filter = 'alpha(opacity='+ speed +')';
            
            if ( speed == target ) {
                clearInterval( obj.opacity );
                endFn && endFn();
            }

        }, 20);
}
上一篇 下一篇

猜你喜欢

热点阅读