在页面滚动时使Bootstrap 4表头在顶部粘滞,可以通过以下步骤实现:
<div>
元素。table
和table-striped
。thead
元素来定义表头行。tr
元素,并添加表头单元格th
。window
对象的scroll
事件来监听页面滚动。position
设置为fixed
,并设置top
属性为0。position
设置为默认值。下面是一个示例代码:
HTML:
<div id="table-container">
<table class="table table-striped">
<thead>
<tr>
<th>表头1</th>
<th>表头2</th>
<th>表头3</th>
</tr>
</thead>
<tbody>
<!-- 表格内容 -->
</tbody>
</table>
</div>
JavaScript:
window.addEventListener('scroll', function() {
var tableContainer = document.getElementById('table-container');
var tableContainerTop = tableContainer.offsetTop;
var tableContainerHeight = tableContainer.offsetHeight;
var tableHeader = tableContainer.querySelector('thead tr');
if (window.pageYOffset > tableContainerTop) {
tableHeader.style.position = 'fixed';
tableHeader.style.top = '0';
} else {
tableHeader.style.position = '';
}
});
这样,当页面滚动时,表头行将会在顶部粘滞显示。你可以根据需要自定义表格的样式和其他行为。
推荐的腾讯云相关产品:腾讯云云服务器(CVM)和腾讯云对象存储(COS)。
领取专属 10元无门槛券
手把手带您无忧上云