定时器 - 简单运动

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

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

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

<body>
    <input type="button" value="开始" id="start">
    <div class="box" id="box"></div>
    <script>
        // 简单运动
        // 获取元素
        var start = document.getElementById("start");
        var box = document.getElementById("box");

        //信号量. 每次给它重新赋值, 实现变化
        //信号量初始值必须与属性初始值保持一致, left:0 所以nowLeft=0
        var nowLeft = 0;

        // 点击开始按钮,让 box 向右运动
        start.onclick = function () {
            //定时器, 制作运动过程
            setInterval(function () {
                nowLeft += 10;
                box.style.left = nowLeft + "px";
            }, 100);
        };


    </script>
</body>

</html>
posted @ 2021-08-16 13:52  charonmomo  阅读(26)  评论(0编辑  收藏  举报