动画封装四:用json实现多条样式的缓动运动

来源:互联网 发布:神漫软件下载 编辑:程序博客网 时间:2024/06/06 00:59

基础样式:

/* 用通配符清除默认样式减少代码量,实际项目应对用到的标签清除默认样式*/ *{margin: 0;padding: 0;list-style: none;outline: none;}div{position: absolute;left: 0;width: 200px;height: 200px;line-height: 200px;background-color: pink;font-size:80px;text-align:center;}
html 骨架:

<button id='btn'>运动</button><div id='div'>变</div>
javascript 结构:

var div = document.getElementById('div');var json = {'width':50,'height':50,'line-height':50,            'left':200,'top':200,'opacity':60,            'zIndex':2,'font-size':16           };btn.onclick =  function () {    animate(div,json,over);}// 这里定义一个回调函数function over() {    alert('当前动画执行完毕');}/** * 用json实现多条样式的缓动运动函数封装 * @param  {[type]}   obj       运动对象 * @param  {[type]}   json      目标距离 * @param  {Function} fn        回调函数 * @return {[type]}             null */function animate(obj,json,fn) {    clearInterval(obj.timer);    var step = 0;    var current = 0; // 当前值    obj.timer = setInterval(function() {        var flag = true;        for(var k in json) {            // 对 opacity 初始化处理,乘上100来参与缓动运算            if( k == 'opacity' ) {                current = Math.round( getStyle(obj,k) * 100 ) ;                if(getStyle(obj,k) == 0) {                  json[k] *=100;               }            } else if( k == 'z-index' ||  k == 'zIndex') {                // 如果得不到z-index ,那么赋0处理                current = getStyle(obj,k) || 0;            } else {                // 把字符串变成纯数字 若是top,left等没定义默认给0                current = parseInt( getStyle(obj,k) ) || 0;            }            step = (json[k] - current) / 10;            step = step > 0 ? Math.ceil(step) : Math.floor(step);            current += step;            // 对 opacity 进行样式处理            if( k == 'opacity' ) {                // 把不透明度除100 还原 ,并赋值。                obj.style[k] = current / 100 ;                obj.style['filter'] = 'alpha(opacity='+ current / 100 +')';            } else if ( k == 'z-index' || k == 'zIndex' ) {                current = json[k];                // 直接变化,不需渐变                obj.style.zIndex = json[k];            } else {                obj.style[k] = current + 'px';            }            if( current != json[k] ) {                flag = false;            }        }        if(flag) {            clearInterval(obj.timer);            if(fn) {                fn();            }        }    },10);}// 得到对象的当前样式函数封装function getStyle(obj,attr) {   return obj.currentStyle?obj.currentStyle[attr]:window.getComputedStyle(obj,null)[attr]; }


0 0
原创粉丝点击