使用js缓动动画封转

来源:互联网 发布:电缆线路设计软件 编辑:程序博客网 时间:2024/05/17 07:02
/** * @param ele  目标元素 * @param json  json对象 * @param fn    回调函数 */function animate(ele,json,fn){    //清除定时器    clearInterval(ele.timer);    ele.timer = setInterval(function(){        //判断动作是否执行完毕        var bool = true;        //遍历json的属性        for(var k in json){            //获取当前位置            var leader = parseInt(getStyle(ele,k)) || 0;            //获取速度            var step = (json[k] - leader)/10;            //判定速度的正负,并对其进行向上取整或者向下取整  保证能停止计时器            step = step>0?Math.ceil(step):Math.floor(step);            //将初始值变化            leader = leader + step;            //移动            ele.style[k] = leader + "px";            //清除定时器            //判断: 目标值和当前值的差大于步长,就不能跳出循环            //不考虑小数的情况:目标位置和当前位置不相等,就不能清除清除定时器。            if (json[k] !== leader){                bool = false;            }        }        //当所有动作执行完毕,就清理定时器        if (bool){            clearInterval(ele.timer);            //如果还有回调函数,继续执行回调函数            if (fn){                fn();            }        }    },10);}/** * 获取元素样式 * @param ele  目标元素 * @param attr  元素属性 * @returns {*} 返回属性值 */function getStyle(ele,attr){    if(window.getComputedStyle){        return window.getComputedStyle(ele,null)[attr];    }    return ele.currentStyle[attr];}


下面我们就来测试一波

html代码如下:

<body>    <button>来回运动</button>    <div></div></body>


var btn = document.getElementsByTagName("button")[0];var div = document.getElementsByTagName("div")[0];btn.onclick = function () {    var json1 = {"left":300,"top":200,"width":300,"height":200};    var json2 = {"left":10,"top":30,"width":100,"height":100};    animate(div,json1, function () {        animate(div,json2, function () {            animate(div,json1,function(){                animate(div,json2);            });        });    });}

运行结果: