当前位置:首页 > JavaScript

js 实现ctrl f

2026-03-01 02:10:55JavaScript

监听键盘快捷键组合

在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"]'));

兼容性考虑

确保代码在不同浏览器中正常工作:

js 实现ctrl f

// 使用keyCode作为后备方案
document.addEventListener('keydown', function(event) {
    if (event.ctrlKey && (event.key === 'f' || event.keyCode === 70)) {
        event.preventDefault();
        openSearchBox();
    }
});

标签: jsctrl
分享给朋友:

相关文章

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callbac…

js实现计算器

js实现计算器

实现基础计算器功能 使用JavaScript创建一个基础计算器需要处理数字输入、运算符逻辑和结果显示。以下是一个简单的实现示例: let currentInput = '0'; let previo…

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(func,…

js怎么实现异步

js怎么实现异步

异步实现方法 JavaScript中实现异步操作主要通过以下几种方式: Promise Promise是ES6引入的异步解决方案,用于处理异步操作的成功或失败状态。 const promise =…