html - CSS 冻结了带有水平滚动的表格的第一列。滚动位于 HTML 页面的主体上
问题描述
对于具有可滚动的冻结列的表,我已经看到了无数的解决方案,例如:
但我所追求的是将滚动放在页面(正文)上,而不是放在桌子上或桌子周围的容器上。
编辑——它只是一个基本的 HTML 表格,它太大而无法完全显示,所以有一个水平滚动。在页面主体上进行水平滚动的原因是用户不必滚动到页面底部就可以水平滚动。
.stickyCol2 tr th:nth-child(1),
.stickyCol2 tr td:nth-child(1){
position: absolute;
width: 50px;
left: 15px;
top: auto;
background-color: #fff;
}
.stickyCol2 tr th:nth-child(2),
.stickyCol2 tr td:nth-child(2){
position: absolute;
width: 60px;
left: 86px;
top: auto;
background-color: #fff;
}
<div class="stickyCol2">
<table>
<thead>
<tr>
<th>item 1</th>
<th>item 2</th>
<th>item 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>item 1</td>
<td>item 2</td>
<td>item 3</td>
</tr>
</tbody>
</table>
</div>
解决方案
以下是一些工作代码以及可用于微调解决方案的说明。
主要思想是您将要固定的列的内容包装在span
元素中,您将其固定在屏幕的左侧(使用 CSS)并赋予它们等于其内容的宽度(我在我的代码中只使用了一列)。
var cellWidth=$('th:first-child').width();
$('th:first-child, td:first-child').each(function() {
$(this).wrapInner('<span></span>');
$(this).find('span').attr('style', 'width:'+cellWidth+'px;');
})
您将 a 添加margin-left
到表中,等于固定列的总宽度(如果必须,您必须使用 Javascript 计算),以便固定列不会与可滚动单元格内容重叠。
$('table').attr('style', 'margin-left:'+cellWidth+'px;');
之后,使用 jQuery,您可以检测 body 的滚动(或者对于溢出的容器,工作方式相同)并在 span 上应用负 transform:translateY
属性。
$(window).on('scroll', function() {
var scr = -$(this).scrollTop();
console.log(scr);
$('th:first-child span, td:first-child span').css('transform', 'translateY(' + scr + 'px)');
})
这是一个工作小提琴,希望它能给你最初的推动。 https://jsfiddle.net/scooterlord/ndxjg1b0/21/
推荐阅读
- javascript - Shopify 表单自定义字段
- access-token - Microsoft Identity Manager MIM 的缺点
- protocol-buffers - 运行 protoc 时是否可以指定输出版本?
- google-app-maker - 连接到自定义 SQL 数据库
- javascript - 错误 TS2315:类型“ElementRef”不是通用材料角度
- database - 为不同的应用程序使用相同的用户名/密码数据库?
- javascript - 还有另一种获取地图的方法吗?
- slack - 发送消息时松弛 channel_not_found
- ios - 'EnumeratedSequence<[CGPoint]>' 类型的值没有成员 'compactMap'
- python - c程序SWIG到python给出'ImportError:动态模块没有定义init函数'