// * @param {object} obj [dom节点对象] // * @param {object} options [属性和目标值的对象] // * @param {boolean} islinear [是否是匀速动画] // * @param {function} fnend [动画结束时执行的函数] function animate(obj,options,islinear,fnend){ //设置默认是匀速动画 if(islinear == undefined){ islinear = true; } //防止多次操作开启多个定时器 clearinterval(obj.timer); //速度/步长 var ispeed = 0; obj.timer = setinterval(function(){ //代表是否终止所有的动画 var isstopall = true; for(var attr in options){ //isstopcurrent代表是否终止当前动画,由于在循环定时器中,所以每次执行都会变为false,代表不终止当前动画 var isstopcurrent = false; //获取当前的最新的值 var current = parsefloat(getcomputedstyle(obj,false)[attr]); //opacity属性的处理 if(attr == 'opacity'){ //1.乘以100是为了计算 //2.四舍五入是为了处理小数 current = math.round(current*100); } //匀速动画的处理 if(islinear){ //确定匀速动画的速度 if(current > options[attr]){ ispeed = -10; }else{ ispeed = 10; } //匀速动画终止条件 if(math.abs(options[attr] - current) < math.abs(ispeed)){ //匀速动画终止后的处理:如果最后一次动画不够一个速度的话,直接到达目标值 if(attr == 'opacity'){ obj.style.opacity = options[attr] / 100; }else{ obj.style[attr] = options[attr] + 'px'; } //代表终止当前的动画 isstopcurrent = true; }else{ //代表当前的动画还没有结束,所以不能终止所有的动画 isstopall = false; } //减速动画的处理 }else{ //确定减速动画的速度 ispeed = (options[attr] - current)/10; ispeed = ispeed > 0 ? math.ceil(ispeed) : math.floor(ispeed); //减速动画的终止条件 if(!ispeed){ //代表终止当前的动画 isstopcurrent = true; }else{ //代表当前的动画还没有结束,所以不能终止所有的动画 isstopall = false; } } //如果不终止当前动画,运动 if(!isstopcurrent){ if(attr == 'opacity'){ obj.style.opacity = (current + ispeed)/100 ; }else{ obj.style[attr] = current + ispeed + 'px'; } } } //如果终止所有动画,清除定时器 if(isstopall){ clearinterval(obj.timer); //动画执行完毕后的执行函数 typeof fnend == 'function' && fnend(); } },30) } function getscrolltop(){ return window.pageyoffset || document.documentelement.scrolltop || document.body.scrolltop; } function getscrollleft(){ return window.pagexoffset || document.documentelement.scrollleft || document.body.scrollleft; }