You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML输入搜索时文本高亮实现求助:修复侧边栏搜索高亮功能

Fixing Search Text Highlighting for Your Sidebar Project List

Let's walk through the issues with your current code and fix the highlighting feature step by step:

Key Issues in Your Original Code

  1. CSS Class Mismatch: Your JavaScript adds a search-found class to matches, but your CSS targets a highlight class—they need to match!
  2. Unpreserved Original Content: Every keyup event modifies the link's HTML directly, leading to nested highlight spans (e.g., typing "Pro" then "Pr" breaks existing highlights) and loss of the original text structure.
  3. Case Sensitivity & Text Alteration: Converting everything to uppercase changes the original text's case in the UI.
  4. No Empty Input Reset: When clearing the search box, the highlights don't revert to the original content.

Fixed Code Implementation

1. Updated CSS

Make sure your highlight class matches what we'll use in JavaScript (let's stick with your existing .highlight selector for consistency):

.sidebar .nav-link .highlight {
  background-color: #7b9d6f;
  padding: 2px 4px; /* Optional: Add padding for better visibility */
  border-radius: 3px; /* Optional: Soften edges */
}

2. Improved JavaScript

We'll cache the original content of each link to avoid modifying it directly, use case-insensitive regex for matches, and handle empty input properly:

// Cache original content of each link when the page loads
document.addEventListener('DOMContentLoaded', function() {
  const projectLinks = document.querySelectorAll('#projectlist .nav-link');
  projectLinks.forEach(link => {
    link.dataset.originalContent = link.innerHTML;
  });
});

// Initialize filter input and add event listener
const filterInput = document.getElementById('filterInput');
filterInput.addEventListener('keyup', filterNames);

function filterNames() {
  const filterValue = filterInput.value.trim();
  const projectList = document.getElementById('projectlist');
  const listItems = projectList.querySelectorAll('li.nav-item');

  // Escape special regex characters in user input to avoid errors
  function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }

  listItems.forEach(item => {
    const link = item.querySelector('.nav-link');
    const originalContent = link.dataset.originalContent;

    // If input is empty, reset all items to original state
    if (!filterValue) {
      item.style.display = '';
      link.innerHTML = originalContent;
      return;
    }

    // Create case-insensitive regex to find matches
    const escapedFilter = escapeRegExp(filterValue);
    const matchRegex = new RegExp(escapedFilter, 'gi');
    const hasMatch = originalContent.toUpperCase().includes(filterValue.toUpperCase());

    if (hasMatch) {
      item.style.display = '';
      // Wrap matches in highlight span, preserving original case
      const highlightedContent = originalContent.replace(matchRegex, match => `<span class="highlight">${match}</span>`);
      link.innerHTML = highlightedContent;
    } else {
      item.style.display = 'none';
    }
  });
}

3. HTML (No Changes Needed)

Your existing HTML structure is fine—we just added a data attribute via JavaScript to store original content, so no edits are required here.

How This Works

  • Original Content Caching: We save each link's initial HTML in a data-original-content attribute when the page loads, so we can always revert to it.
  • Safe Regex Matching: The escapeRegExp function ensures user input with special characters (like * or +) doesn't break the regex.
  • Case-Insensitive Highlighting: Using the gi regex flags (global + case-insensitive) finds all matches without altering the original text's case.
  • Empty Input Handling: Clearing the search box resets all links to their original state and shows all items.

Give this a try—your search filtering will work as before, and matching text will now be properly highlighted!

内容的提问来源于stack exchange,提问作者PvDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:59:57