js方框水平移动测试代码

2020-05-01
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        #box {
            width: 200px;
            height: 200px;
            border: 1px solid red;
        }
    </style>
</head>
<body>

<input type="button" value="移动到400" id="btn">
<input type="button" value="移动到800" id="btn2">

<div id="box"></div>
<script>
    let btn = document.getElementById('btn');
    let btn2 = document.getElementById('btn2');
    let box = document.getElementById('box');
    btn.onclick = function () {
        move(this, 400, 9);
    };

    btn2.onclick = function () {
        move(this, 800, 8);
    };

    function move(element, target, step) {
        let current = document.defaultView.getComputedStyle(box, null).marginLeft;
        let timeId = setInterval(function () {
            current = parseInt(current);
            console.log(current);
            if (target > current){
                // 目标在右方
                if ((target - current) > step) {
                    current += step;
                } else if ((target - current) <= step) {
                    current = target;
                    clearInterval(timeId);
                }
            } else {
                // 目标在左方
                if ((current - target) > step) {
                    current -= step;
                } else if ((current - target) <= step) {
                    current = target;
                    clearInterval(timeId);
                }
            }

            box.style.marginLeft = current + 'px';
        }, 100);
    }
</script>
</body>
</html>