在此示例中,当给出tbody属性为"显示为块"结果是预期的。但当给出"显示为table-header-group"我不能将表行(tr)宽度设置为相应的th。请帮帮我。
段:
var $table = $('table.scroll'),
$bodyCells = $table.find('tbody tr:first').children(),
colWidth;
// Adjust the width of thead cells when window resizes
$(window).resize(function() {
// Get the tbody columns width array
colWidth = $bodyCells.map(function() {
return $(this).width();
}).get();
alert("width:" + colWidth);
// Set the width of thead columns
$table.find('thead tr').children().each(function(i, v) {
$(v).width(colWidth[i]);
});
}).resize(); // Trigger resize handler

table.scroll {
width: 100%;
/* Optional */
/* border-collapse: collapse; */
border-spacing: 0;
border: 2px solid black;
}
table.scroll tbody {
display: block;
}
table.scroll thead {
display: table-header-group;
}
thead tr th {
height: 30px;
line-height: 30px;
/*text-align: left;*/
}
table.scroll tbody {
height: 100px;
overflow-y: auto;
overflow-x: hidden;
}
tbody {
border-top: 2px solid black;
}
tbody td,
thead th {
// width: 20%; /* Optional */ border-right: 1px solid black;
}
tbody td:last-child,
thead th:last-child {
border-right: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="scroll">
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
<th>Head 3</th>
<th>Head 4</th>
<th>Head 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
</tr>
<tr>
<td>Content 1</td>
<td>Lorem ipsum dolor sit amet.</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
</tr>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
</tr>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
</tr>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
</tr>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
</tr>
<tr>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
</tr>
</tbody>
</table>
&#13;
答案 0 :(得分:0)
Ajax数据表将是您的最佳解决方案。这是您可以实现的链接。 Data table example 和Scrolling example。在第二个链接中找到滚动示例
$(document).ready(function() {
$('#example').DataTable( {
scrollY: '50vh',
scrollCollapse: true,
paging: false
} );
} );
如果需要,您还可以使用像素设置滚动功能。使用这个插件你不需要操纵表。它将重新排列表格。