封装缓动动画函数

来源:互联网 发布:access 软件开发步骤 编辑:程序博客网 时间:2024/05/16 09:34
<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <style>        *{            margin: 0;            padding: 0;        }        #box{            width: 100px;            height: 100px;            background-color: pink;            position: absolute;            left: 0;            top: 50px;        }    </style></head><body><button id="btn200">200</button><button id="btn400">400</button><div id="box"></div></body></html><script>    var btn200 = document.getElementById("btn200");    var btn400 = document.getElementById("btn400");    var box = document.getElementById("box");    btn200.onclick = function () {        animate(box,200);    }    btn400.onclick = function () {        animate(box,400);    }    function animate(obj,target){        //盒子本身位置+步长        clearInterval(obj.timer);        obj.timer = setInterval(function(){            var step = (target-obj.offsetLeft)/10; //步长            step = step>0?Math.ceil(step):Math.floor(step);//步长取整            obj.style.left = obj.offsetLeft + step + "px";            if(target == obj.offsetLeft){                clearInterval(obj.timer);            }        },30);    }</script>
0 0
原创粉丝点击