当前位置:首页 > JavaScript

js 实现ctrl f

2026-01-30 11:05:05JavaScript

在JavaScript中实现类似Ctrl+F的搜索功能

通过监听键盘事件和操作DOM元素,可以在网页中实现类似浏览器原生Ctrl+F的搜索功能。以下是具体实现方法:

监听Ctrl+F组合键

document.addEventListener('keydown', function(event) {
  if (event.ctrlKey && event.key === 'f') {
    event.preventDefault();
    showSearchBox();
  }
});

创建搜索框UI

function showSearchBox() {
  const searchBox = document.createElement('div');
  searchBox.innerHTML = `
    <input type="text" id="searchInput" placeholder="搜索...">
    <button id="searchNext">下一个</button>
    <button id="searchPrev">上一个</button>
    <span id="matchCount">0/0</span>
  `;
  searchBox.style.position = 'fixed';
  searchBox.style.top = '10px';
  searchBox.style.right = '10px';
  searchBox.style.zIndex = '9999';
  document.body.appendChild(searchBox);

  document.getElementById('searchInput').focus();
}

实现搜索逻辑

let currentIndex = -1;
let matches = [];

function performSearch() {
  const searchTerm = document.getElementById('searchInput').value.toLowerCase();
  if (!searchTerm) return;

  const textNodes = [];
  const walker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    null,
    false
  );

  let node;
  while (node = walker.nextNode()) {
    if (node.nodeValue.trim()) {
      textNodes.push(node);
    }
  }

  matches = [];
  textNodes.forEach((node, i) => {
    const content = node.nodeValue.toLowerCase();
    let pos = content.indexOf(searchTerm);
    while (pos !== -1) {
      matches.push({
        node,
        pos,
        length: searchTerm.length
      });
      pos = content.indexOf(searchTerm, pos + 1);
    }
  });

  updateMatchCount();
}

高亮和导航搜索结果

function highlightMatch(index) {
  if (matches.length === 0 || index < 0 || index >= matches.length) return;

  const match = matches[index];
  const range = document.createRange();
  range.setStart(match.node, match.pos);
  range.setEnd(match.node, match.pos + match.length);

  // 移除之前的高亮
  const oldHighlights = document.querySelectorAll('.search-highlight');
  oldHighlights.forEach(el => {
    const parent = el.parentNode;
    parent.replaceChild(document.createTextNode(el.textContent), el);
    parent.normalize();
  });

  // 添加新高亮
  const span = document.createElement('span');
  span.className = 'search-highlight';
  span.style.backgroundColor = 'yellow';
  range.surroundContents(span);

  // 滚动到高亮位置
  span.scrollIntoView({ behavior: 'smooth', block: 'center' });

  currentIndex = index;
  updateMatchCount();
}

function updateMatchCount() {
  const countElement = document.getElementById('matchCount');
  countElement.textContent = `${currentIndex + 1}/${matches.length}`;
}

添加事件监听器

document.getElementById('searchInput').addEventListener('input', performSearch);
document.getElementById('searchNext').addEventListener('click', () => {
  if (matches.length === 0) return;
  const nextIndex = (currentIndex + 1) % matches.length;
  highlightMatch(nextIndex);
});
document.getElementById('searchPrev').addEventListener('click', () => {
  if (matches.length === 0) return;
  const prevIndex = (currentIndex - 1 + matches.length) % matches.length;
  highlightMatch(prevIndex);
});

CSS样式

.search-highlight {
  background-color: yellow;
  color: black;
}

#searchInput {
  padding: 5px;
  margin-right: 5px;
}

#matchCount {
  margin-left: 10px;
  color: #666;
}

注意事项

  • 此实现会在整个页面内容中搜索,包括动态加载的内容
  • 搜索是区分大小写的,可以通过调整代码改为不区分大小写
  • 对于大量文本内容,可能需要优化搜索性能
  • 可以添加Esc键监听来关闭搜索框
  • 考虑添加对正则表达式的支持以增强搜索功能

这种实现方式提供了基本的搜索功能,可以根据具体需求进一步扩展和完善。

js 实现ctrl f

标签: jsctrl
分享给朋友:

相关文章

css3结合js制作

css3结合js制作

CSS3 结合 JavaScript 制作动态效果 CSS3 和 JavaScript 结合可以实现丰富的动态效果,包括动画、交互和响应式设计。以下是几种常见的实现方式: CSS3 动画与 Java…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现验证码

js实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas…

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js实现全屏

js实现全屏

实现全屏的基本方法 使用JavaScript实现全屏功能主要依赖Element.requestFullscreen()方法。现代浏览器均支持此API,但不同浏览器可能需要添加前缀。 // 触发全屏…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…