冻结表头,同时允许动态宽度 [英] Freeze table header while allowing dynamic widths
问题描述
我看到的用于冻结表标题行的解决方案是创建另一个只包含标题的表,使第一个表的标题隐藏。这只有在预设宽度时才起作用。但我想要我的表的列的大小根据其内容。我还希望表不具有固定的高度,因为我想在设备上使用它,并希望使用所有可用空间(减去保留一个用于头)
The solutions I've seen for freezing a table header row is by creating another table with just the header, making the first table's header hidden. This works only if the widths are pre set. But I want my table's columns to be sized according to their contents. I also want the table to not have a fixed height, because I want to use it across devices, and want to use all available space (minus reserved one for a header)
推荐答案
这种方法类似于你的其他问题。除了在这种情况下,< tbody>
是视口,我们需要给它的行 display:table
,因此它们的宽度可以手动设置。
The approach to this is similar to your other question. Except in this case, the <tbody>
is the viewport, and we'll need to give its rows display: table
, so their widths can be manually set.
我添加了一些JS来基本克隆顶行最多的内容,并将它们作为视觉上隐藏的行附加到< thead>
,以帮助动态地将其移动到正确的宽度。我也重新调整了CSS。如果< th>
内容长于< td>
内容,则注释布局仍会中断。
I've added some JS to essentially clone the top rows with the most content and append them as visually hidden rows to <thead>
to help get it to the right width dynamically. I've also re-tuned the CSS. Note layout still breaks if <th>
content is longer than <td>
content.
$(function() {
var $table = $('table');
var $body = $table.find('tbody');
var rowTexts = $body.find('tr').map(function() {
return $(this).text().trim();
}).toArray().sort(function(a, b) {
return (a.length > b.length) ? -1 : (a.length < b.length) ? 1 : 0;
});
if (rowTexts.length > 5) {
rowTexts = rowTexts.slice(0, 5);
}
var $head = $table.find('thead');
rowTexts.forEach(function(text) {
var $hiddenRow = $body.find('tr:contains(' + text + ')').clone().addClass('hidden');
$head.append($hiddenRow);
});
});
body {
height: 100%;
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
text-align: left;
margin-top: 44px;
width: 100%;
}
td,
th {
border-bottom: 1px solid black;
height: 44px;
line-height: 44px;
padding: 0 1em;
}
tr.hidden td {
border: 0;
height: 0;
line-height: 0;
overflow: hidden;
}
thead {
display: table;
position: fixed;
top: 0;
width: 100%;
}
thead tr:not(.hidden) {
background: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Key that's longer than usual</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value that's longer than usual</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Key</td>
<td>Value</td>
</tr>
<tr>
<td>Last Key</td>
<td>Last Value</td>
</tr>
</tbody>
</table>
这篇关于冻结表头,同时允许动态宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!