cari

Rumah  >  Soal Jawab  >  teks badan

使用js实现简单的发射子弹的效果,结果只能发射一颗子弹没有办法做到连发

var timer = null;
switch (e.keyCode) {
        case 37:
            div1.style.left = div1.offsetLeft - 10 + "px";
            break;
        case 39:
            div1.style.left = div1.offsetLeft + 10 + "px";
            break;
        case 38:
            div1.style.top = div1.offsetTop - 10 + "px";
            break;
        case 40:
            div1.style.top = div1.offsetTop + 10 + "px";
            break;
        case 81:
            div22 = document.createElement("div");
            div22.style.width = "20px";
            div22.style.height = "20px";
            div22.style.top = div1.offsetTop + 65 +"px";
            div22.style.left = div1.offsetLeft + 260+"px";
            div22.className = "pp";
            div1.appendChild(div22)
            var timer  = setInterval(function(){
                div22.style.left = div22.offsetLeft + 30+ "px";
                if(div22.offsetLeft >= 800){
                    div1.removeChild(div22);
                    clearInterval(timer);
                }
            },300)
只能同时发射一颗子弹,第一颗子弹没有消亡的时候发射第二颗,第一颗子弹会固定在屏幕上,以此类推.目前只知道是timer的问题,但是 不知道要怎么解决 额额额


高洛峰高洛峰2928 hari yang lalu768

membalas semua(1)saya akan balas

  • 三叔

    三叔2016-11-19 14:02:22

    不知道对不对:

    var array = [];
    var div22;
    setInterval(function(){
        array.forEach(function(div, index) {
            div.style.left = div.offsetLeft + 30+ "px";
            if(div.offsetLeft >= 800){
                div1.removeChild(div22);
                array.spilce(index, 1);
            }
        });
    },300)
    switch (e.keyCode) {
        case 37:
            div1.style.left = div1.offsetLeft - 10 + "px";
            break;
        case 39:
            div1.style.left = div1.offsetLeft + 10 + "px";
            break;
        case 38:
            div1.style.top = div1.offsetTop - 10 + "px";
            break;
        case 40:
            div1.style.top = div1.offsetTop + 10 + "px";
            break;
        case 81:
            div22 = document.createElement("div");
            div22.style.width = "20px";
            div22.style.height = "20px";
            div22.style.top = div1.offsetTop + 65 +"px";
            div22.style.left = div1.offsetLeft + 260+"px";
            div22.className = "pp";
            div1.appendChild(div22);
            array.push(div22);
    }


    balas
    0
  • Batalbalas