javascript 为什么“style.height/width”不适用于变量,只适用于设置值?

b5buobof  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(210)

目前正在尝试使用Flexbox和一些DOM操作来显示一个16x16的网格。这是我想在网格容器中创建一个16块行的代码:

// Gets grid's dimensions
const gridContainer = document.getElementById("grid-container");
const gridHeight = gridContainer.offsetHeight;
const gridWidth = gridContainer.offsetWidth;

function createBlock() {
  const gridBlock = document.createElement("div");
  gridBlock.style.height = gridHeight / 16;
  gridBlock.style.width = gridWidth / 16;
  gridBlock.style.border = "1px solid black";
  gridContainer.appendChild(gridBlock);
}

function createRow() {
  for (let i = 0; i < 16; i++) {
    createBlock();
  }
}

createRow();
#grid-container {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  background-color: #FFF;
  height: 40rem;
  width: 40rem;
}
<div id="grid-container"></div>

如果我使用console.log gridBlock. style. height and width,**这些值都在那里,**但它们不会创建一个块。
如果我将它们设置为一个固定值,比如40px,那么代码将完美地运行,网格行也将按预期显示在那里。
我知道我可以用CSS Grid和其他方法创建它们,但Flexbox和DOM操作是我正在学习的ATM,这需要同时使用两者。任何帮助都是非常感谢的:)

aij0ehis

aij0ehis1#

您需要向width/height附加一个单位,因为这些属性的无单位值对CSS没有任何意义。

function createBlock() {
    const gridBlock = document.createElement("div");
    gridBlock.style.height = `${gridHeight / 16}px`;
    gridBlock.style.width = `${gridWidth / 16}px`;
    gridBlock.style.border = "1px solid black";
    gridContainer.appendChild(gridBlock);
}

如果您来自React世界,则需要习惯这一点,因为React会在内部智能地将数值转换为像素值:

{/* Identical in React world */}
<div style={{ width: 16 }} />
<div style={{ width: '16px' }} />
toe95027

toe950272#

既然你说你想学习CSS,你可以用一个类和一些calc()来做这件事,我在这里为边框和背景添加了一些颜色,只是为了显示它的工作。

// Gets grid's dimensions
const gridContainer = document.getElementById("grid-container");

function createBlock() {
  const gridBlock = document.createElement("div");
  gridBlock.classList.add("sixteenth");
  gridContainer.appendChild(gridBlock);
}

function createRow() {
  for (let i = 0; i < 16; i++) {
    createBlock();
  }
}

createRow();
#grid-container {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  background-color: #FFF;
  height: 40rem;
  width: 40rem;
}

.sixteenth {
  width: calc(100% /16);
  height: calc(100% /16);
  border: solid 1px green;
  background-color: #ddffdd44;
}
<div id="grid-container"></div>

相关问题