애니메이션 패키지 2: 수평 완화 운동 실현

기본 스타일 구조:
/*                ,                 */ 
*{margin: 0;padding: 0;list-style: none;outline: none;}
div{position: absolute;left: 0;width: 200px;height: 200px;background-color: pink;}

html 골격:
<button id="btn1">  400px</button>
<button id="btn2">  200px</button>
<button id="btn3">  0px</button>
<div id='div'></div>

javascript 구조:
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var btn3 = document.getElementById('btn3');
var div = document.getElementById('div');
var finish = true;
btn1.onclick = function () {
    animateOver(div,400,over,finish);
}
btn2.onclick = function () {
    animateOver(div,200,null,finish);
}
btn3.onclick = function () {
    animateOver(div,0,null,finish);
}

//        ,       
function animateOver(obj,target,fn,flag) {
    if( flag ) {
        animate(obj,target,fn);
        return ;
    }
    flag = false;
}
//           
function over() {
    alert('      ');
}

/**
 *               
 * @param  obj           
 * @param  target        
 * @param  fn            
 * @return           null
 */
function animate(obj,target,fn) {
    if( target == parseInt( getStyle(obj,'left') ) ) {
        alert( '           ,         !' );
        return;
    }
    obj.timer = null;
    clearInterval(obj.timer);
    var step = 0;
    obj.timer = setInterval(function() {
        step = (target - obj.offsetLeft) / 10;
        step = step > 0 ? Math.ceil(step) : Math.floor(step);
        obj.style.left = obj.offsetLeft + step + 'px';
        finish = false;
        if( obj.offsetLeft == target ) {
            clearInterval(obj.timer);
            if(fn) {
                fn();
            }
            finish = true;
        }
    },10);
}
//             
function getStyle(obj,attr) {
    return obj.currentStyle?obj.currentStyle[attr]:window.getComputedStyle(obj,null)[attr];
}

좋은 웹페이지 즐겨찾기