要在网页上实现查找表格中的文本并平滑滚动到相应位置,同时突出显示该行,你可以使用HTML、CSS和JavaScript来完成这个任务。以下是一个简单的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Scroll and Highlight</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<input type="text" id="searchInput" onkeyup="searchAndScroll()" placeholder="Search for names..">
<table id="dataTable">
<tr><th>Firstname</th><th>Lastname</th></tr>
<tr><td>John</td><td>Doe</td></tr>
<tr><td>Jane</td><td>Doe</td></tr>
<!-- Add more rows as needed -->
</table>
<script src="script.js"></script>
</body>
</html>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
.highlight {
background-color: yellow;
}
function searchAndScroll() {
const input = document.getElementById('searchInput');
const filter = input.value.toUpperCase();
const table = document.getElementById('dataTable');
const trs = table.getElementsByTagName('tr');
for (let i = 0; i < trs.length; i++) {
const tr = trs[i];
let found = false;
for (let j = 0; j < tr.cells.length; j++) {
const td = tr.cells[j];
if (td) {
const txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
}
if (found) {
tr.classList.add('highlight');
tr.scrollIntoView({ behavior: 'smooth', block: 'center' });
} else {
tr.classList.remove('highlight');
}
}
}
searchAndScroll
函数在每次按键时被调用。highlight
类到该行,并使用 scrollIntoView
方法平滑滚动到该行。highlight
类。scrollIntoView
的 smooth
行为可能在某些旧浏览器中不受支持。可以使用 polyfill 或自定义动画来解决。.highlight
类不会与其他样式冲突,可以通过更具体的选择器或增加权重来解决。通过这种方式,你可以为用户提供一个友好的界面来搜索和定位表格中的信息。
领取专属 10元无门槛券
手把手带您无忧上云