JS - 抖动运动框架

//抖动运动框架
function shake(obj,attr,endFn){
	if(obj.onoff) return;	//当前的onoff=false
	obj.onoff = true;
	var pos = parseInt(getStyle(obj,attr)); 
	var arr = []; //10,-10,8,-8,6,-6......
	var timer = null;
	var num = 0;
	
	for(var i = 20; i > 0; i -= 2){
		arr.push(i,-i);
	}
	arr.push(0); //最后加上0

	obj.timer = setInterval(function(){
		obj.style[attr] = pos + arr[num] + 'px';
		num++;
		if(num === arr.length){
			clearInterval(obj.timer);
			endFn && endFn();//判断回调函数
			obj.onoff = false;
		} 
	},50)
}
//获取css样式
function getStyle(obj,attr){ 
    if(obj.currentStyle){ 
    	return obj.currentStyle[attr]; 
    }else{ 
        return getComputedStyle(obj)[attr]; 
    } 
}

你可能感兴趣的:(JavaScript)