【发布时间】:2015-02-03 20:04:12
【问题描述】:
:)
我知道这个问题被问了很多,但我尝试了很多解决方案,但无法使其正常工作。
我需要使用固定标题使表格的 tbody 可滚动。
开始我的表是动态构建的并且非常大。 19 列,约 800 行。
首先我使用了 jquery 数据表插件。 表格进入容器后:
var tbl = createFilter('readDataTbl', '', condition);
$('#tableDiv').empty().append(tbl);
$('#readDataTbl').dataTable({
"scrollY": "200px",
"scrollCollapse": true,
"paging": false
});
但这会在 x 中创建一个滚动,并且标题会像这样被冻结:
然后我尝试了如下的css解决方案:
<style>
table {
border-collapse: collapse;
width: 100%;
}
thead {
text-align:left;
display: table;
float: left;
width: 100%;
}
thead tr {
display: table-row;
width: 100%;
}
tbody {
display: block;
height: 120px;
overflow: auto;
float: left;
width: 100%;
}
tbody tr {
display: table;
width: 100%;
}
tbody tr {
height: 18px;
}
tbody td {
padding:1px 8px;
}
th, td {
width: 25%;
}
tr:after{ /* IE8 fix */
content: ".";
margin-left: -3px; /* to hide the content above tr */ /* not necessary if you are ok with 1px gap */
visibility: hidden;
}
</style>
但这只会在 tbody 中造成这样的混乱:
然后我尝试了Here的方法 调整 THs 宽度后: css:
<style>
thead, tbody { display: block; }
tbody {
height: 100px; /* Just for the demo */
overflow-y: auto; /* Trigger vertical scroll */
overflow-x: hidden; /* Hide the horizontal scroll */
}
</style>
js:
var tbl = createFilter('readDataTbl', '', condition);
$('#tableDiv').empty().append(tbl);
var $table = $('table');
var $bodyCells = $table.find('tbody tr:first').children();
// Get the tbody columns width array
var colWidth = $bodyCells.map(function () {
return $(this).width();
}).get();
// Set the width of thead columns
$table.find('thead tr').children().each(function (i, v) {
$(v).width(colWidth[i]);
});
然后我注意到 TH 的长文本使它们变得更大:
什么可以帮助我实现目标? 考虑在 TH 中插入 div,但不确定..
谢谢! : ]
【问题讨论】:
标签: javascript jquery css html-table jquery-datatables