为什么每个新形状都会向左生成 150 像素的形状?

why do my shapes get generated 150pxs to the left with every new shape?

我正在开发这个游戏,终于想出了如何将我的代码重写成一个最小的例子,我为我为这个例子删掉了多少代码而感到自豪。所以我的代码在点击屏幕时开始 运行,点击后,我的 createShape1() 函数运行,创建一个灰色矩形。它开始下降到屏幕底部,然后再次调用 CreateShape1() 重新开始整个过程​​。然而,第二个形状应该与第一个形状处于相同的位置,但它向左移动了 150pxs 并最终重置并向下移动。 这是我的 HTML:

<!DOCTYPE html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tetris</title>
    <link rel="stylesheet" href="styleSheets/main.css">
    <script src = "js/jquery.js"></script>
    <script src = "js/main.js"></script>
  </head>
  <body>
    <div id="container" style= "height: 650px; width: 500px; background: black; position: relative">
      <div class= "grid">
      </div>
    </div>

  </body>
</html>

CSS:

.grid {
    background-image: repeating-linear-gradient(0deg,transparent,transparent 49px,#88F 49px,#88F 50px),
                    repeating-linear-gradient(-90deg,transparent,transparent 49px,#88F 49px,#88F 50px);
    background-size: 50px 50px;
    top: 0px;
    height: 651px;
    position: absolute;
    width: 501px;
}

JS:

var svgNS = "http://www.w3.org/2000/svg";
countO = 0;
function createShape1() {
  var endB1 = 650;
  var newEndB = endB1; //used to set boundaries bottom
  var elem = document.getElementById("container");
  var outer = document.createElementNS(svgNS, "svg"); //creates full transparent shape
  countO++;
  elem.append(outer);
  outer.id = "outer" + countO;
  outer.style.background = "grey";
  outer.style.height = "100px";
  outer.style.width = "150px";
  outer.style.left = "150px";
  outer.style.top = "0px";
  outer.style.position = "relative";
  outer.style.transform = "rotate(0deg)"
  var t = setInterval(down, 100); // calls down() function every second
  var yPos = parseInt(outer.style.top);
  var h = parseInt(outer.style.height);
  var ymath = yPos + h;
  function down() {  // moves shape down by 50px
    if (ymath < newEndB) {
      yPos += 50;
      ymath = yPos + h;
      outer.style.top = yPos +'px';

    } else {
      clearInterval(t);
    }
  }
};

var shapes = [createShape1];
function randShape() {
  shapes[0]();
};

window.addEventListener("click", startGame, {once: true})

function startGame() {
  randShape()
  var t = setInterval(randShape, 1200)
}


发生的情况是您的脚本在每次调用时都会添加一个新元素。由于它们有position:relative,它们是紧挨着生成的,不能相交。即使您使用 down() 函数移动它们,它们也只是在视觉上相对于它们的原始位置移动,技术上仍然占据它们生成的 space。尝试更改

outer.style.position = "relative";

outer.style.position = "absolute";

Here is a pen

或者,您可以让脚本在创建新块之前删除前一个块,这也应该有效。