在JavaScript中实现类似Ctrl+F(查找)的效果,通常涉及到在网页上创建一个搜索框,允许用户输入关键词,并高亮显示页面中匹配该关键词的所有实例。以下是一个简单的实现示例:
<!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="Enter text to search...">
<button onclick="highlight()">Search</button>
<div id="content">
<!-- Your content goes here -->
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>
<script>
function highlight() {
const searchText = document.getElementById('searchInput').value;
const regex = new RegExp(searchText, 'gi'); // 'g' for global, 'i' for case-insensitive
const content = document.getElementById('content');
// Remove previous highlights
const highlightedElements = document.getElementsByClassName('highlight');
while (highlightedElements.length > 0) {
highlightedElements[0].parentNode.replaceChild(highlightedElements[0].firstChild, highlightedElements[0]);
}
// Highlight new matches
let match;
while ((match = regex.exec(content.innerHTML)) !== null) {
const span = document.createElement('span');
span.className = 'highlight';
const before = content.innerHTML.slice(0, match.index);
const after = content.innerHTML.slice(regex.lastIndex);
content.innerHTML = before + span.outerHTML + match[0] + span.outerHTML + after;
regex.lastIndex += span.outerHTML.length - match[0].length;
}
}
</script>
</body>
</html>
通过上述方法,可以在网页上实现一个基本的Ctrl+F查找和高亮功能。
没有搜到相关的文章