js 实现ctrl f
监听键盘快捷键组合
在JavaScript中,可以通过监听keydown事件来检测用户是否按下了Ctrl + F组合键。以下是实现代码示例:
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key === 'f') {
event.preventDefault(); // 阻止浏览器默认的查找行为
openSearchBox(); // 调用自定义搜索函数
}
});
创建搜索界面
需要创建一个搜索框供用户输入搜索内容。可以通过动态生成DOM元素或直接修改现有HTML结构实现:
<div id="searchBox" style="display: none; position: fixed; top: 10px; right: 10px;">
<input type="text" id="searchInput" placeholder="搜索...">
<button id="searchButton">搜索</button>
<button id="closeButton">关闭</button>
</div>
实现搜索功能
搜索功能可以通过遍历页面文本内容并高亮匹配项来实现:
function performSearch(searchTerm) {
const elements = document.querySelectorAll('body *:not(script):not(style)');
let found = false;
elements.forEach(element => {
if (element.childNodes.length === 1 && element.childNodes[0].nodeType === Node.TEXT_NODE) {
const text = element.textContent;
if (text.includes(searchTerm)) {
element.innerHTML = element.innerHTML.replace(
new RegExp(searchTerm, 'gi'),
match => `<span style="background-color: yellow">${match}</span>`
);
found = true;
}
}
});
if (!found) {
alert('未找到匹配内容');
}
}
处理搜索框交互
需要为搜索框添加事件处理程序:
function openSearchBox() {
const searchBox = document.getElementById('searchBox');
searchBox.style.display = 'block';
document.getElementById('searchInput').focus();
}
document.getElementById('closeButton').addEventListener('click', function() {
document.getElementById('searchBox').style.display = 'none';
// 清除高亮
document.querySelectorAll('span[style="background-color: yellow"]').forEach(el => {
const parent = el.parentNode;
parent.textContent = parent.textContent;
});
});
document.getElementById('searchButton').addEventListener('click', function() {
const searchTerm = document.getElementById('searchInput').value;
if (searchTerm) {
performSearch(searchTerm);
}
});
改进搜索性能
对于大型文档,上述方法可能性能不佳。可以考虑以下优化:
// 使用TreeWalker API更高效地遍历文本节点
function optimizedSearch(searchTerm) {
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
null,
false
);
let found = false;
let node;
while (node = walker.nextNode()) {
const text = node.nodeValue;
if (text.includes(searchTerm)) {
const span = document.createElement('span');
span.style.backgroundColor = 'yellow';
const parent = node.parentNode;
parent.replaceChild(span, node);
span.appendChild(document.createTextNode(text));
found = true;
}
}
return found;
}
添加导航功能
可以实现查找下一个/上一个匹配项的功能:
let currentHighlightIndex = -1;
let highlights = [];
function navigateSearch(direction) {
if (highlights.length === 0) return;
// 移除当前高亮的焦点样式
if (currentHighlightIndex >= 0) {
highlights[currentHighlightIndex].style.outline = 'none';
}
// 计算新的索引
currentHighlightIndex = (currentHighlightIndex + direction + highlights.length) % highlights.length;
// 添加新焦点样式并滚动到元素
highlights[currentHighlightIndex].style.outline = '2px solid red';
highlights[currentHighlightIndex].scrollIntoView({ behavior: 'smooth', block: 'center' });
}
// 在performSearch函数中收集所有高亮元素
highlights = Array.from(document.querySelectorAll('span[style="background-color: yellow"]'));
兼容性考虑
确保代码在不同浏览器中正常工作:
// 使用keyCode作为后备方案
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && (event.key === 'f' || event.keyCode === 70)) {
event.preventDefault();
openSearchBox();
}
});






