碰壁反彈

效果圖:

碰壁反彈 (2).gif

源代碼:

<!doctype html>
<html>
<head>
    <meta charset='utf-8'/>
    <title>碰壁反彈</title>
    <style type="text/css">
        #content{
            height: 500px;
            width: 500px;
            border:  1px solid #000;
            position: relative;
        }
        .boll {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: red;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
    <div id="content">
        
    </div>
    <script type="text/javascript">
        // 獲取圍欄
        var content = document.querySelector('#content');
        // 產(chǎn)生小球,并使其運動
        function createAndRun(){
            // 創(chuàng)建一個小球
            var boll =document.createElement('div');
            boll.className = 'boll';
            content.appendChild(boll);

            // 使用定時器讓小球移動
            var speendX = Math.floor(Math.random()*10);
            var speendY = Math.floor(Math.random()*10);
            setInterval(function  () {

                // 判斷小球是否撞左右墻
                if (boll.offsetLeft+boll.offsetWidth >= content.offsetWidth 
                    || boll.offsetLeft < 0) {
                    speendX*=-1;
                }
                // 判斷小球是否撞上下墻
                if (boll.offsetTop + boll.offsetHeight >= content.offsetHeight
                    || boll.offsetTop <0 ) {
                    speendY*=-1;
                }
                // 
                boll.style.left = boll.offsetLeft + speendX +'px';
                boll.style.top = boll.offsetTop + speendY +'px';
            },10);
        }
        createAndRun();
        // setInterval(createAndRun,1000);
    </script>
</body>
</html>

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容