用原生js固定表格表头
时间: 2023-10-10 08:15:47 浏览: 133
要固定表格的表头,可以使用原生 JavaScript 实现以下步骤:
1. 获取表格元素和表头元素。
2. 获取表头元素的高度。
3. 添加滚动事件监听器,当滚动时,判断表格顶部是否超过表头元素的底部,如果超过,则将表头元素设置为固定定位,并将其 top 值设置为 0;否则将其设置为相对定位。
4. 在窗口大小变化时,重新获取表头元素的高度。
以下是一个示例代码:
```html
<style>
.fixed-header th {
position: fixed;
top: 0;
background-color: #fff;
z-index: 1;
}
</style>
<table id="example-table">
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<!-- 表格内容 -->
</tbody>
</table>
<script>
const table = document.getElementById('example-table');
const header = table.querySelector('thead th');
const headerHeight = header.offsetHeight;
function handleScroll() {
if (table.getBoundingClientRect().top < headerHeight) {
header.classList.add('fixed-header');
} else {
header.classList.remove('fixed-header');
}
}
window.addEventListener('scroll', handleScroll);
window.addEventListener('resize', () => {
headerHeight = header.offsetHeight;
});
</script>
```
阅读全文
相关推荐














