动态生成表格时单元格高度计算值与实际显示不符导致溢出容器的问题求助
嗨,我来帮你排查这个问题!你遇到的这种“数学上算得对,但显示就是不对”的情况,大概率是浏览器渲染表格时的默认样式和像素舍入在搞鬼,咱们一步步拆解:
核心原因分析
表格默认的单元格间距
HTML的<table>元素默认带有border-spacing属性(一般默认值是2px),这个间距是加在单元格之间的。你有10行单元格,行与行之间就有9个间距,每个2px的话就额外占了18px高度,直接让表格总高度超过div的设置值,导致最后一行溢出。小数像素的舍入误差
当你用0.7*pageWidth/nRows计算单元格高度时,结果很可能是带小数的像素值(比如pageWidth是1001px的话,0.7*1001=700.7px,除以10就是70.07px)。浏览器渲染时会对这种小数像素取整,10个单元格的误差累加起来,就会让表格总高度和div高度出现偏差,要么溢出要么留白。表格和行的默认样式
除了间距,<table>、<tr>本身还可能带有默认的margin、padding或者border,这些也会偷偷占用额外空间。
解决办法
咱们直接针对这些问题修改代码,保证表格完美贴合div:
第一步:修正表格的默认样式(CSS部分)
在现有CSS里添加表格重置样式,去掉多余的间距和边距:
body { background-color: darkblue; } #tableDiv { margin-left: 15%; margin-top: 5%; } .testing { background-color: green; /* 这里你之前加了引号,CSS颜色值不需要引号哦 */ } /* 新增表格重置样式 */ #test_table { width: 100%; height: 100%; border-collapse: collapse; /* 合并单元格边框,去掉间距 */ border-spacing: 0; margin: 0; padding: 0; } #test_table tr, #test_table td { margin: 0; padding: 0; border: none; /* 去掉默认边框 */ }
第二步:优化JS里的尺寸设置逻辑
把固定像素改为百分比,让单元格自适应div大小,同时修正table的id(之前的id有空格,会导致CSS选择器失效):
const pageWidth = document.documentElement.scrollWidth; const nRows = 10; const nColumns = 10; const tableDiv = document.getElementById("tableDiv"); tableDiv.style.width = 0.7*pageWidth + "px"; tableDiv.style.height = 0.7*pageWidth + "px"; tableDiv.style.backgroundColor = "yellow"; // 动态生成指定尺寸的表格 function constructTable(nR, nC) { const tbl = document.createElement("table"); tbl.id = "test_table"; // 把空格改成下划线,避免选择器问题 let tRow; let tCell; for (let r = 0; r < nR; r++) { tRow = document.createElement("tr"); tbl.appendChild(tRow); for (let c = 0; c < nC; c++) { tCell = document.createElement("td"); tCell.className = "testing"; tRow.appendChild(tCell); } } return tbl; } function showTable(t) { tableDiv.innerHTML = ""; tableDiv.appendChild(t); const dynamicSizeCells = document.getElementsByClassName("testing"); for (let i = 0; i < dynamicSizeCells.length; i++) { // 用百分比代替固定像素,自适应div尺寸 dynamicSizeCells[i].style.width = `${100/nColumns}%`; dynamicSizeCells[i].style.height = `${100/nRows}%`; dynamicSizeCells[i].style.backgroundColor = "green"; } console.warn("Div width is " + tableDiv.style.width + ", div height is " + tableDiv.style.height + "; cell width is " + dynamicSizeCells[0].style.width + ", cell height is " + dynamicSizeCells[0].style.height); } const theTable = constructTable(nRows, nColumns); showTable(theTable);
第三步:额外小修正
你之前CSS里.testing的background-color加了双引号,这是无效的,已经帮你去掉了。
这样修改后,表格会完全占满div的空间,没有额外的间距和误差,最后一行就不会溢出啦!
备注:内容来源于stack exchange,提问作者Quack E. Duck

