封装变速动画函数

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        #dv {
            width: 200px;
            height: 200px;
            background-color: cyan;
            position: absolute;
        }
    </style>
</head>
<body>
<button id="btn">移动到400</button>
<button id="btn1">移动到800</button>
<script src="common.js"></script>
<div id="dv"></div>
<script>
    function f1(element,json,fn) {
        //清除定时器
        clearInterval(element.timeId)
        //添加定时器
        element.timeId=setInterval(function () {
            //假设到达目标位置
            var flag=true;
            for (var attr in json){
                //获取元素的当前位置
                var current = parseInt(getStyle(element,attr));
                //目标的值
                var target=json[attr];
                //移动的步数
                var step=(target-current)/10;
                //判断左右移动
                step=step>0?Math.ceil(step):Math.floor(step);
                //移动
                current+=step;
                //赋值
                element.style[attr]=current+"px";
                //如果有一个当前的位置,不等于目标位置,让flag=false
                if (current!=target){
                    flag=false
                }
            }
            //循环完后,如果flag为true, 这证明到达目标位置
            if (flag){
                clearInterval(element.timeId);
                //判断如果用户传了fn, 则调用
                if (fn){
                    fn();
                }
            }
        },20)
    }



    my$("btn").onclick = function () {
        f1(my$("dv"), {"width": 400, "height": 400, "left": 500, "top": 300}, function () {

            f1(my$("dv"), {"width": 30, "height": 30, "left": 600, "top": 400}, function () {

                f1(my$("dv"), {"width": 100, "height": 50, "left": 300, "top": 0})
            })
        })
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_44388393/article/details/86497931