原生js 实现小球来回弹动

256 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .container {
        position: relative;
    }
    .move-dom{
        position: absolute;
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background:red;
        left: 50px;
    }
</style>
<body>
    <div class="container">
        <div class="move-dom">

        </div>
    </div>
</body>
<script>
    var move = document.querySelector(".move-dom");
    moveDom(move);
    function moveDom(dom) {
        let windowWidth = document.documentElement.clientWidth
        dom.style.left = "50px";
        var flag = false;
        setInterval(function() {
            let left = parseInt(dom.style.left);
            if(!flag){
                dom.style.left = left + 10 + "px";
                if(parseInt(dom.style.left)  >= windowWidth - 100 ){
                    flag = !flag;
                };
            }else{
                dom.style.left = left - 10 + "px"; 
                if(parseInt(dom.style.left) <= 0 ){
                    flag = !flag;
                };
            }
        },50);
    }
</script>
</html>