1. 程式人生 > 其它 >函式的封裝(運動封裝)

函式的封裝(運動封裝)

技術標籤:javascript

實現盒子的向左向右自動移動

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        #box {
            position: absolute;
            left: 0;
            top: 100px;
            width: 100px;
            height: 100px;
            background: skyblue;
        }
    </style>
</head>

<body>
    <button>向右移動</button>
    <button>向左移動</button>
    <div id="box"></div>
    <script>
        //動畫
        var o = document.getElementById('box');

        //向右
        document.getElementsByTagName('button')[0].onclick = function () {
            move(o, 500, 5, 'left')
        };

        document.getElementsByTagName('button')[1].onclick = function () {
            move(o, 0, 5, 'left')
        };

        //target  終點位置
        //step     每次的移動距離
        //obj       移動的目標物件
        function move(obj, target, step, attr) {
            //根據起點和終點之間的關係,判定速度的正負
            step = parseFloat(getComputedStyle(obj, null)[attr]) > target ? -step : step;//起點>終點?
            clearInterval(obj.timer);//清除
            obj.timer = setInterval(function () {
                var l = parseFloat(getComputedStyle(o, null)[attr]);//當前的div的屬性值
                var speed = l + step;//  +5  +(-5)      每一次移動到的位置
                //到達邊界時,
                if (speed >= target && step > 0 || speed <= target && step < 0) {
                    clearInterval(t);
                    speed = target;//邊界值
                }
                obj.style[attr] = speed + "px";
            }, 20);
        }
    </script>
</body>

</html>

在這裡插入圖片描述