use*_*331 -1 html css twitter-bootstrap
我试图冻结我的 html 表 (thead) 中的第一行,但是当我尝试以下 CSS 代码时:
table {
width: 100% !important;
}
thead, tbody {
display: block;
}
tr:after {
content: ' ';
display: block;
visibility: hidden;
clear: both;
}
thead th {
height: 30px;
}
tbody {
height: 500px;
overflow-y: auto;
}
Run Code Online (Sandbox Code Playgroud)
thead 与 tbody 的大小不同。tbody 是可滚动的,thead 处于固定位置,但不一样,tr 聚集在一起。这是我的 HTML:
<table id="MVCGridTable_Grid" class="table table-striped table-bordered">
<thead>
<tr>
<th>aaa</th>
<th>aaa</th>
<th>aaa</th>
<th>aaa</th>
<th>aaa</th>
</tr>
</thead>
<tbody>
<tr>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
</tr>
<tr>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
</tr>
<tr>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
</tr>
<tr>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
</tr>
<tr>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
<td>
aaa
</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
这是我试图放在一起的DEMO,但我添加的Bootstrap似乎不起作用,所以请原谅缺乏样式:
这是我得到的结果:
为此,您需要将表格包装在一个元素中position: relative,一个height或max-height(注意某些版本的 IE 有/在calc()in 方面遇到了一些问题max-height)可由浏览器翻译成物理大小,并应用于th/td粘性<thead>类中的每一个的sticky-top或者,如果你愿意的话,下面的CSS:
position: sticky;
top: 0;
z-index: 1020;
Run Code Online (Sandbox Code Playgroud)
看到它工作:
position: sticky;
top: 0;
z-index: 1020;
Run Code Online (Sandbox Code Playgroud)
"use strict";
var stickySituation = function stickySituation(o) {
return $("".concat(o, " .sticky-top")).css('position') === 'fixed';
};
var updateStickyHeader = function updateStickyHeader(i, e) {
var cell = $("tbody tr>*:nth-child(".concat(i + 1, ")"), $(e).closest('table')).eq(0)[0];
if (cell) {
var box = cell.getBoundingClientRect();
$(e).css({
top: 0,
width: box.width,
height: box.height,
left: box.left
});
}
};
$(window).on('load', function () {
var sh = '.table-responsive.sticky-headers';
$('thead th').addClass('sticky-top bg-white');
if (stickySituation(sh)) {
$(sh).css({
paddingTop: $('tbody tr>*:nth-child(1)', sh).eq(0).css('height')
});
$(window).on('resize', function () {
$('thead th').each(updateStickyHeader);
});
$(window).trigger('resize');
}
});Run Code Online (Sandbox Code Playgroud)
.table-responsive {
max-height: 100vh;
/* whatever makes sense */
overflow-y: auto;
}
.table-responsive .sticky-top {
border-top: 0;
border-bottom: 0;
box-shadow: 0 1px 0 0 gainsboro;
/* hack for IE: */ position: fixed;
position: sticky;
}Run Code Online (Sandbox Code Playgroud)
更新:为不支持position: sticky(即:IE)的浏览器添加了 JS 。
现代浏览器只需要23来自脚本的行(它只将sticky-top和bg-white类添加到每个<th>,这显然可以手动完成)。
也就是说,您实际上并不需要现代浏览器中的 JS 部分来使其工作(只要您将类(或 CSS 规则)应用于您的标记,如上所述)。
| 归档时间: |
|
| 查看次数: |
1150 次 |
| 最近记录: |