【问题标题】:Why does "style.height/width" doesn't work with variables, only set values?为什么 \"style.height/width\" 不适用于变量,只能设置值?
【发布时间】:2023-02-06 22:06:44
【问题描述】:

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

HTML:

 <div id="grid-container"></div>

CSS:

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

JavaScript:

// 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();

如果我 console.log gridBlock.style.height 和 width,价值观在那里,但它们不会创建块。

如果我将它们设置为 40px 之类的固定值,代码将完美运行并且网格行按预期存在。

我知道我可以使用 CSS Grid 和其他方法创建它们,但 Flexbox 和 DOM 操作是我正在学习 ATM 的内容,这需要同时使用两者来完成。非常感谢任何帮助:)

【问题讨论】:

  • 你忘了将 px 添加到宽度和高度

标签: javascript css dom flexbox


【解决方案1】:

您需要将一个单位附加到宽度/高度,因为这些属性的无单位值对 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' }} />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    相关资源
    最近更新 更多