模拟乒乓球自由落体,只有上下弹跳,无左右

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #ball {
            position: fixed;
            height: 50px;
            width: 50px;
            border-radius: 50%;
            background: orange;
            left: 200px;
        }
    </style>
</head>
<body>
<div id="ball"></div>
<script>
    //模拟乒乓自由落体
    var ball = document.getElementById('ball');
    var speed = 0;
    //teacher
    const G = 1;
    const UP = 0;
    const DOWN = 1;
    var ballState = DOWN;
    //损耗
    const SPEED_COST = 3;

    //定时
    var timer = setInterval(drop, 1)
    //定义函数 自由落体过程
    function drop() {
        //bottom距离
        var ballY = parseInt(getStyle(ball, 'bottom'));
        if (ballState === DOWN) {//落下
            if (ballY > 0) {
                speed += G;
                //没到底部
                ball.style.bottom = ballY - speed + 'px';
            } else {
                ballState = UP;
                ball.style.bottom = '0px';
                speed -= SPEED_COST;
                if (speed <= 0) {
                    clearInterval(timer)
                }
            }
        } else {
            //弹起
            ball.style.bottom = ballY + speed + 'px';
            speed -= G;
            if (speed === 0) {
                ballState = DOWN;
            }
        }
    }

    //获取指定元素的外部或内部的方法
    function getStyle(ele, cssName) {
        if (window.getComputedStyle)
            return window.getComputedStyle(ele)[cssName]
        else {
            return ele.currentStyle[cssName]
        }
    }
</script>
</body>
</html>

你可能感兴趣的:(js)