Javascript——飞机大战之飞机

会有一股神秘感。 提交于 2020-02-02 09:59:15
<!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>飞机</title>
</head>
<style>
    img {
        position: absolute;
    }
    
    #fly {
        left: 100px;
        top: 200px;
    }
</style>

<body>
    <img src="./images/2.png" style="display: none;" id="pos0">
    <img src="./images/2.png" style="display: none;" id="pos1">
    <img src="./images/2.png" style="display: none;" id="pos2">
    <img src="./images/2.png" style="display: none;" id="pos3">
    <img src="./images/2.png" style="display: none;" id="pos4">
    <img src="./images/1.gif" id="fly">
</body>
<script>
    var fly = document.getElementById("fly");

    document.onkeydown = function(e) {
        var e = e || window.event;
        console.log(e.keyCode);
        switch (e.keyCode) {
            case 37:
                {
                    fly.style.left = fly.offsetLeft - 10 + "px";
                    break;
                }

            case 38:
                {
                    fly.style.top = fly.offsetTop - 10 + "px";
                    break;
                }
            case 39:
                {
                    fly.style.left = fly.offsetLeft + 10 + "px";
                    break;
                }
            case 40:
                {
                    fly.style.top = fly.offsetTop + 10 + "px";
                    break;
                }
            case 32:
                {
                    for (var i = 0; i < 5; i++) {
                        var img = document.getElementById("pos" + i);
                        if (img.style.display == "none") {
                            img.style.display = "block";
                            console.log(fly.offsetLeft + fly.offsetWidth / 2);
                            img.style.left = fly.offsetLeft + fly.offsetWidth / 2 + "px";
                            img.style.top = fly.offsetTop + "px";
                            break;
                        }
                    }
                }
        }
    }
    setInterval(function() {
        for (var i = 0; i < 5; i++) {
            var pos = document.getElementById("pos" + i);
            pos.style.top = pos.offsetTop - 10 + "px";
            if (pos.offsetTop < -7) {
                pos.style.display = "none"
            }
        }
    }, 50)
</script>

</html>

12

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!