簡體   English   中英

使用 js DOM 添加更多網格單元時,如何使整個網格與 flexbox 保持相同大小?

[英]How to make whole grid stay the same size with flexbox when adding more grid cells with js DOM?

我目前正在做 odin 項目 Etch-A-sketch 挑戰。 我目前擁有它,以便使用 JavaScript 創建 16 個行 div,每個行 div 內有 16 個網格方塊。 所以它是一個 16 x 16 的網格。

我如何做到這一點,以便當我將更多網格方塊放入容器中時,整個網格保持相同的大小,並且網格方塊在容器中變得更小或更大,而不會溢出 flexbox 的容器壁?

這是我的代碼筆: https://codepen.io/Alex-Swan/pen/jOyMwzm

Javascript:

/* This function creates 16x16 grid or what ever input the user has given, the event listner at the
 bottom of the function makes it that when a user hovers over a grid square it turns black. 
*/
function fullGrid(e) {
  for (let i = 0; i < e; i++) {
    row = document.createElement("DIV");
    container.appendChild(row);
    row.className = "row";
    for (let i = 0; i < e; i++) {
      square = document.createElement("DIV");
      row.appendChild(square);
      square.className = "gridSquare";
    }
  }
  for (let i = 0; i < gridSquare.length; i++) {
    gridSquare[i].addEventListener("mouseover", () => {
      gridSquare[i].className += " squareBlack";
    });
  }
}

CSS:

.container {
  border: black solid 1px;
  width: 400px;
  height: 400px;
}
.row {
  display: flex;
  height: 6%;
}
.gridSquare {
  border: #444242 solid 1px;
  margin: auto;
  height: 100%;
  width: 33.3%;
}

.squareBlack {
  background-color: black;
}

解決它!

在 JavaScript 中,我通過將 GridSquare 數量除以容器的 400px 大小來計算高度。 另外我將 CSS box-sizing 更改為邊框框。

Javascript:

function fullGrid(e) {
  for (let i = 0; i < e; i++) {
    row = document.createElement("DIV");
    container.appendChild(row);
    row.className = "row";
    for (let i = 0; i < e; i++) {
      square = document.createElement("DIV");
      row.appendChild(square);
      square.className = "gridSquare";
      square.style.width = "100%";               // <----- HERE
      let height = 400 / parseInt(squareAmount);  // <----- HERE
      square.style.height = `${height}px`;       // <----- HERE
    }
  }
  for (let i = 0; i < gridSquare.length; i++) {
    gridSquare[i].addEventListener("mouseover", () => {
      gridSquare[i].className += " squareBlack";
    });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM