移动的小盒子

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }

            .box {
                width: 100px;
                height: 100px;
                background-color: red;
                position: relative;
            }
        </style>
        <script type="text/javascript">
            window.onload = () => {
                //获取div
                var odiv = document.querySelector("div");
                console.log(odiv.offsetWidth);
                //获取body跟html的可见宽度
                var lookWidth = document.body.offsetWidth || document.documentElement.offsetWidth;
                //获取两个按钮
                var btns = document.querySelectorAll("button");
                var length = btns.length;
                var timer = null;
                //每次增加的距离
                var add = 0;
                for (let i = 0; i < length; i++) {
                    btns[0].onclick = function() {
                        var spend = 5;
                        //点击开始元素像右移动
                        if (timer === null) {
                            timer = setInterval(function() {
                                add += spend;
                                odiv.style.left = add+"px";
                                if(add >= lookWidth-odiv.offsetWidth || add <= 0){
                                    //让spend取反
                                    spend = -spend;
                                    console.log(spend);
                                }
                            }, 1);
                        }
                    }
                    btns[1].onclick = function() {
                        //点击暂停
                        clearInterval(timer);
                        timer = null;
                        }
                    }
                console.log(lookWidth);
            }
        </script>
    </head>
    <body>
        <div class="box"></div>
        <button type="button">start</button>
        <button type="button">pause</button>
    </body>
</html>

 

posted @ 2022-03-31 10:50  st-159  阅读(31)  评论(0)    收藏  举报