首页 > 解决方案 > HTML动态表格 - 插入文本时停止扩展高度

问题描述

我有固定宽度和高度的动态表。使用随机函数我得到细胞数(3x3 - 7x7)。表渲染良好。在每个单元格上,我单击了将一个字母写入指向单元格的事件。有一个问题,因为行在高度上扩展。如何阻止它?

https://codepen.io/anon/pen/PdrNVM

let table = document.getElementById('table');

let tableSize = Math.floor((Math.random() * 5) + 3);

console.log(tableSize);
for (i = 0; i < tableSize; i++) {
    let tr = document.createElement('tr');
    for (j = 0; j < tableSize; j++) {
        let td = document.createElement('td');
        let content = document.createTextNode('');
        td.appendChild(content);
        tr.appendChild(td);
    }
    table.appendChild(tr);
}

let tds = document.querySelectorAll("td");

tds.forEach((td) => {
    td.addEventListener("click", function() {
        td.innerHTML = 'p';
    });
});
table {
    width: 200 px;
    height: 200 px;
    table-layout: fixed;
}

td {
    background-color: green;
}
<h2>Click in cell</h2>
<table id='table'></table>

标签: htmlcss

解决方案


只需设置一个适当的heightmax-height喜欢的:

td {
    background-color: green;
    height: 50px;
    max-height: 50px;
}

推荐阅读