我经常发现自己想要一个包含两个(或更多)连续表格的 HTML 文档,我希望这些表格具有相同的格式:每列具有相同的列宽。例如
<table>
<thead><tr><th>Name</th><th>Identifier</th></tr></thead>
<tbody><tr><td>John Smith</td><td>A-64</td></tr></tbody>
</table>
<p>Some text …</p>
<table>
<thead><tr><th>Name</th><th>Id.</th></tr></thead>
<tbody><tr><td>Xavier Ephraim Bloggs III</td><td>A-434-bcf</td></tr></tbody>
</table>
实际上,浏览器会将第二个表格的列渲染得比第一个表格的列宽,原因很简单,因为每个单元格的内容都更宽。
我可以通过硬编码每一列的宽度来解决这个问题,或者使用 HTML width
属性,或者(更好)使用 CSS。但我不想这样做,因为我不知道每栏的宽度。正确的宽度将取决于用户代理对字体的选择、用户屏幕的宽度以及每个单元格的内容(它本身由用户输入生成)。无论如何,UA 比我更擅长决定布局。
我真正想要的是某种方式来布置第二个表格,就好像它是第一个表格的延续一样。我可以通过将它们做成一个单独的表格来做到这一点,中间的段落只是另一行(有足够的 CSS 使其看起来不那么明显),但这看起来很糟糕、邪恶和错误。
<table>
<tr><th>Name</th><th>Id.</th></tr>
<tr><td>John Smith</td><td>A-64</td></tr>
<tr colspan="2"><p>Some text …</p></tr>
<tr><th>Name</th><th>Id.</th></tr>
<tr><td>Xavier Ephraim Bloggs III</td><td>A-434-bcf</td></tr>
</table>
逻辑上它是一个表,但我想在几个部分中呈现一个表,否则它会太长。这表明对表进行编码的逻辑方法是使用两个单独的 <tbody>
。小号:
<table>
<thead><tr><th>Name</th><th>Identifier</th></tr></thead>
<tbody><tr><td>John Smith</td><td>A-64</td></tr></tbody>
<tbody><tr><td>Xavier Ephraim Bloggs III</td><td>A-434-bcf</td></tr></tbody>
</table>
<p>Some text …</p>
我可以使用某种 CSS/HTML5 技巧来移动第二个 <tbody>
(及其标题的副本)添加到段落之后?
最佳答案
最后我得出结论,一个 CSS/HTML 解决方案是不可能的,但它可以用 JQuery 相对简单地完成。
$( "table.splittable" ).each( function() {
$(this).find("tr").first().children().each( function() {
this.setAttribute('width', this.offsetWidth);
} );
var hdrs = $(this).find("tr.move-header");
$(this).find("tr").each( function() {
var tr = this;
$( this.className.split(/\s+/) ).each( function() {
var match = this.match(/^move-to-(.*)$/);
if (match) {
var dest = $('#'+match[1]).get(0);
if (dest.childNodes.length == 0) {
var thead = document.createElement("thead");
dest.appendChild(thead);
hdrs.each( function() {
thead.appendChild(this.cloneNode(true));
} );
dest.appendChild(document.createElement("tfoot"));
dest = dest.appendChild(document.createElement("tbody"));
}
else dest = $(dest).find("tbody").get(0);
dest.appendChild(tr);
}
} );
} );
});
此脚本会查看每个带有 splittable
的表类,等到浏览器呈现它们然后添加 width
将列宽固定为浏览器认为最佳的属性。然后它会查找类别为 move-to-<em>something</em>
的每一行并将其移动到 ID 为 <em>something</em>
的表中.如果目标表没有 <thead>
元素,源表中类为 move-header
的任何行复制到那里。
结果是我需要将内容放在一个表中,并在我希望后面的行移动的地方放一个空的占位符表:
<table class="splittable" id="table1">
<thead><tr class="move-header"><th>Name</th><th>Identifier</th></tr></thead>
<tbody>
<tr class="move-to-table1"><td>John Smith</td><td>A-64</td></tr>
<tr class="move-to-table2"><td>Xavier Ephraim Bloggs III</td><td>A-434-bcf</td></tr>
</tbody>
</table>
<p>Some text …</p>
<table class="table2"></table>
一旦 JavaScript 运行,第二个表将获得标题的副本,最后一行将移到那里。两个表的列宽相同。
这是一个有点丑陋的解决方案,并且在没有 JavaScript 的情况下不会很好地降级。但这是我迄今为止想到的最好的。
关于css - 一致的 HTML 表格尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23847428/