移动div发射子弹-onkeydown事件

215 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            width: 200px;
            height: 200px;
            position: absolute;
            left: calc(50% - 50px);
            top: calc(50% - 50px);
            background: url(bcb.png) 0 /cover;
        }

        .bullet {
            width: 10px;
            height: 15px;
            background: gold;
            border-radius: 5px 5px 0 0;
            box-shadow: 0 5px 2px yellow;
        }
    </style>
</head>

<body>
    <div id="demo">

    </div>
</body>
<script>
    let demo = document.getElementById('demo')
    //魔法数字
    const KEY_CODE = {
        W: 87,
        S: 83,
        A: 65,
        D: 68,
        J: 74,
        ENTER: 13
    }
    window.onkeydown = e => {
        console.log(e.keyCode);//得出当前按键的ASCII
        //按对应的字母使div移动
        switch (e.keyCode) {
            case KEY_CODE.W:
                demo.style.top = (demo.offsetTop - 10) + 'px'
                break;
            case KEY_CODE.S:
                demo.style.top = (demo.offsetTop + 10) + 'px'
                break;
            case KEY_CODE.A:
                demo.style.left = (demo.offsetLeft - 10) + 'px'
                break;
            case KEY_CODE.D:
                demo.style.left = (demo.offsetLeft + 10) + 'px'
                break;
            case KEY_CODE.J:
                fight()
                break;
            default:
                break;
        }
    }
    function fight() {
        let bullet = document.createElement('div')
        //在底部添加子弹div
        document.body.appendChild(bullet)
        //给子弹添加class为bullet
        bullet.classList.add('bullet')
        bullet.style.left = demo.offsetLeft + demo.offsetWidth / 2 - bullet.offsetWidth / 2 + 'px'
        bullet.style.top = demo.offsetTop - bullet.offsetHeight - 10 + 'px'
    }
    setInterval(() => {
        //获取页面中所有的子弹数组
        let bullets = document.getElementsByClassName('bullet')
        for (let i = 0; i < bullets.length; i++) {
            let bullet = bullets[i]
            bullet.style.top = bullet.offsetTop - 10 + 'px'
            //判断子弹的顶点位置小于50,消失
            if (bullet.offsetTop < -50) {
                bullet.remove()
            }
        }
    }, 100)

</script>

</html>