JavaScript 页面搜索定位功能的实现通常涉及以下几个基础概念:
以下是一个简单的实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search and Highlight</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<input type="text" id="searchInput" placeholder="Search...">
<button onclick="searchAndHighlight()">Search</button>
<div id="content">
<p>This is a sample text to demonstrate the search and highlight functionality.</p>
<p>Another paragraph with more text for testing purposes.</p>
<!-- More content here -->
</div>
<script>
function searchAndHighlight() {
const searchText = document.getElementById('searchInput').value;
const regex = new RegExp(searchText, 'gi');
const content = document.getElementById('content');
// Remove previous highlights
const highlightedElements = document.querySelectorAll('.highlight');
highlightedElements.forEach(el => el.classList.remove('highlight'));
if (searchText === '') return;
// Search and highlight
const walker = document.createTreeWalker(content, NodeFilter.SHOW_TEXT, null, false);
let node;
while (node = walker.nextNode()) {
if (node.textContent.includes(searchText)) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = node.textContent.replace(regex, match => `<span class="highlight">${match}</span>`);
while (tempDiv.firstChild) {
node.parentNode.insertBefore(tempDiv.firstChild, node);
}
node.parentNode.removeChild(node);
}
}
// Scroll to the first match
const firstMatch = document.querySelector('.highlight');
if (firstMatch) {
firstMatch.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}
</script>
</body>
</html>
通过上述方法和代码示例,可以实现一个基本的页面搜索和高亮功能,并根据具体需求进行优化和调整。
领取专属 10元无门槛券
手把手带您无忧上云