固定表格表头和前三行,剩余行无限滚动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>固定表头和前三行,表格自动滚动</title>
</head>
<body>
<div class="scroll-table">
<table class="thead-table">
<thead>
<tr>
<th width="68px">序号</th>
<th width="130px">姓名</th>
<th width="120px">年龄</th>
<th width="130px">性别</th>
<th width="100px">手机号</th>
</tr>
</thead>
<tbody id="thead-tbody"></tbody>
</table>
<div class="scroll-box">
<table class="stripe-odd" id="scroll-box-table">
<thead>
<tr>
<th width="68px">序号</th>
<th width="130px">姓名</th>
<th width="120px">年龄</th>
<th width="130px">性别</th>
<th width="100px">手机号</th>
</tr>
</thead>
<tbody id="scroll-box-tbody"></tbody>
</table>
</div>
</div>
<script>
var tableData = []
for (let i = 0; i < 3; i++) {
tableData.push({
'序号': i + 1,
'姓名': '姓名' + (i + 1),
'年龄': '年龄' + (i + 1),
'性别': '性别' + (i + 1),
'手机号': '手机号' + (i + 1)
})
}
var translateY = -152
var intervalInt = ''
var maxHeight = (tableData.length + 1) * 34
const scrollBoxTable = document.getElementById('scroll-box-table')
const theadTbody = document.getElementById('thead-tbody')
const scrollBoxTbody = document.getElementById('scroll-box-tbody')
function init () {
let top3Html = ''
let tbodyHtml = ''
for (let i = 0; i < tableData.length; i++) {
const item = tableData[i]
if (i < 3) { // 渲染固定的前三行
top3Html += `
<tr>
<td>${item['序号']}</td>
<td>${item['姓名']}</td>
<td>${item['年龄']}</td>
<td>${item['性别']}</td>
<td>${item['手机号']}</td>
</tr>
`
}
tbodyHtml += `
<tr>
<td>${item['序号']}</td>
<td>${item['姓名']}</td>
<td>${item['年龄']}</td>
<td>${item['性别']}</td>
<td>${item['手机号']}</td>
</tr>
`
}
theadTbody.innerHTML = top3Html
scrollBoxTbody.innerHTML = tbodyHtml
setTranslateY(translateY)
if (tableData.length > 7) {
tableData.slice(3).forEach(item => {
tbodyHtml += `
<tr>
<td>${item['序号']}</td>
<td>${item['姓名']}</td>
<td>${item['年龄']}</td>
<td>${item['性别']}</td>
<td>${item['手机号']}</td>
</tr>
`
})
scrollBoxTbody.innerHTML = tbodyHtml
this.initInterval()
}
}
function setTranslateY (y) {
scrollBoxTable.style.transform = `translateY(${y}px)`
}
function initInterval () {
clearInterval(intervalInt)
intervalInt = setInterval(() => {
if (translateY * -1 === maxHeight + 26) { // 表格最后一行滚动到顶部
translateY = -152
} else {
translateY--
}
setTranslateY(translateY)
}, 16)
}
init()
</script>
<style>
* {
margin: 0;
padding: 0;
}
.scroll-table {
margin: 20px;
position: relative;
height: 298px;
width: 548px;
overflow: hidden;
border: 1px solid #000;
}
.thead-table {
line-height: 34px;
border-collapse: collapse;
}
.thead-table th {
height: 33px;
padding: 0;
border-collapse: collapse;
border: none;
border-bottom: 1px solid #5ea2ff;
}
.thead-table td {
text-align: center;
border: none;
}
.scroll-box th {
height: 33px;
}
.scroll-box td {
height: 34px;
text-align: center;
}
.scroll-box {
height: 240px;
position: absolute;
top: 138px;
overflow: hidden;
}
</style>
</body>
</html>