列表表头固定内容首尾循环滚动
时间: 2024-04-13 15:10:01 浏览: 90
您可以使用JavaScript和CSS来实现固定列表表头和循环滚动的效果。以下是一个简单的示例代码:
HTML结构:
```
<div class="table-container">
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
<td>Row 1, Column 3</td>
<td>Row 1, Column 4</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
<td>Row 2, Column 3</td>
<td>Row 2, Column 4</td>
</tr>
<!-- more rows -->
</tbody>
</table>
</div>
```
CSS样式:
```
.table-container {
position: relative;
height: 300px; /* 设置容器高度 */
overflow: auto; /* 开启滚动条 */
}
table {
width: 100%;
border-collapse: collapse;
}
thead {
position: sticky;
top: 0;
background-color: white;
}
th, td {
padding: 8px;
border: 1px solid black;
}
tbody:before,
tbody:after {
content: "";
display: block;
height: 50px; /* 设置滚动空白区域高度 */
}
tbody:before {
margin-top: -50px;
}
tbody:after {
margin-bottom: -50px;
}
```
JavaScript代码:
```
const table = document.querySelector('table');
const tbody = table.querySelector('tbody');
table.addEventListener('scroll', () => {
const topOffset = table.getBoundingClientRect().top;
const tbodyOffset = tbody.getBoundingClientRect().top;
const tbodyHeight = tbody.getBoundingClientRect().height;
if (topOffset > tbodyOffset) {
// 向下滚动时,移动最后一行到第一行之前
const lastRow = tbody.lastElementChild;
const firstRow = tbody.firstElementChild;
if (lastRow.getBoundingClientRect().bottom < tbodyHeight) {
tbody.insertBefore(lastRow, firstRow);
}
} else {
// 向上滚动时,移动第一行到最后一行之后
const firstRow = tbody.firstElementChild;
const lastRow = tbody.lastElementChild;
if (firstRow.getBoundingClientRect().top > 0) {
tbody.insertBefore(firstRow, lastRow.nextElementSibling);
}
}
});
```
这段代码使用`position: sticky;`将表头固定在视口顶部,并且使用`::before`和`::after`伪元素来创建顶部和底部的空白区域。在滚动时,根据滚动方向移动最后一行或第一行到对应的位置,实现列表的循环滚动效果。
阅读全文
相关推荐












