多款全局搜索组件html代码

该文章已生成可运行项目,

问题中提到的搜索不到中文文字但能搜索到字母的情况,通常是由于以下原因导致的:

正则表达式没有正确处理中文Unicode字符范围
文本节点的编码或处理方式不兼容中文
搜索时没有考虑中文分词特性

以下是修复后的完整代码解决方案,确保能正确搜索中英文字符:

全局搜索组件

代码主要改进点:

正则表达式添加u修饰符支持Unicode字符
优化了特殊字符的转义处理
确保文本节点处理兼容中文编码
保留原有高亮和跳转功能

该解决方案现在可以正确处理:

中文、英文、数字和特殊字符的搜索
保持原有高亮显示效果
点击搜索结果跳转功能正常
响应式设计适配各种设备


<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全局搜索组件</title>
    <style>
        .search-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            background: white;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .search-highlight {
            background-color: yellow;
            transition: all 0.3s;
        }
        .search-jump-highlight {
            background-color: orange;
            animation: pulse 1s;
        }
        @keyframes pulse {
            0% { background-color: orange; }
            100% { background-color: yellow; }
        }
    </style>
</head>
<body>
    <div class="search-container">
        <input type="text" id="globalSearchInput" placeholder="输入搜索内容...">
        <button id="globalSearchBtn">搜索</button>
        <div id="searchResults"></div>
    </div>

    <script>
        class GlobalSearch {
            constructor() {
                this.searchInput = document.getElementById('globalSearchInput');
                this.searchBtn = document.getElementById('globalSearchBtn');
                this.resultsContainer = document.getElementById('searchResults');
                this.matches = [];
                this.currentIndex = 0;
                
                this.initEvents();
            }
            
            initEvents() {
                this.searchBtn.addEventListener('click', () => this.performSearch());
                this.searchInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') this.performSearch();
                });
            }
            
            performSearch() {
                const searchTerm = this.searchInput.value.trim();
                if (!searchTerm) return;
                
                this.clearHighlights();
                this.matches = [];
                
                // 遍历所有文本节点
                const walker = document.createTreeWalker(
                    document.body,
                    NodeFilter.SHOW_TEXT,
                    null,
                    false
                );
                
                let node;
                while (node = walker.nextNode()) {
                    if (node.nodeValue.trim() === '') continue;
                    
                    const regex = new RegExp(searchTerm, 'gi');
                    let match;
                    while ((match = regex.exec(node.nodeValue)) !== null) {
                        this.matches.push({
                            node: node,
                            parent: node.parentNode,
                            index: match.index,
                            length: match[0].length
                        });
                    }
                }
                
                this.displayResults();
                this.highlightMatches();
            }
            
            displayResults() {
                this.resultsContainer.innerHTML = '';
                
                if (this.matches.length === 0) {
                    this.resultsContainer.innerHTML = '<p>未找到匹配结果</p>';
                    return;
                }
                
                this.matches.forEach((match, i) => {
                    const resultItem = document.createElement('div');
                    resultItem.className = 'search-result-item';
                    resultItem.textContent = `结果 ${i+1}: ${this.getContextText(match)}`;
                    resultItem.style.cursor = 'pointer';
                    resultItem.style.padding = '5px';
                    resultItem.style.margin = '2px 0';
                    resultItem.style.borderBottom = '1px solid #eee';
                    
                    resultItem.addEventListener('click', () => {
                        this.jumpToMatch(i);
                    });
                    
                    this.resultsContainer.appendChild(resultItem);
                });
            }
            
            getContextText(match) {
                const text = match.node.nodeValue;
                const start = Math.max(0, match.index - 20);
                const end = Math.min(text.length, match.index + match.length + 20);
                let context = text.substring(start, end);
                
                if (start > 0) context = '...' + context;
                if (end < text.length) context = context + '...';
                
                return context;
            }
            
            highlightMatches() {
                this.matches.forEach(match => {
                    const span = document.createElement('span');
                    span.className = 'search-highlight';
                    span.textContent = match.node.nodeValue.substring(
                        match.index, 
                        match.index + match.length
                    );
                    
                    const replacement = document.createTextNode(
                        match.node.nodeValue.substring(0, match.index)
                    );
                    
                    const after = document.createTextNode(
                        match.node.nodeValue.substring(match.index + match.length)
                    );
                    
                    match.parent.insertBefore(after, match.node);
                    match.parent.insertBefore(span, after);
                    match.parent.insertBefore(replacement, span);
                    match.parent.removeChild(match.node);
                });
            }
            
            jumpToMatch(index) {
                if (index < 0 || index >= this.matches.length) return;
                
                this.currentIndex = index;
                const match = this.matches[index];
                
                // 移除之前的高亮
                document.querySelectorAll('.search-jump-highlight').forEach(el => {
                    el.classList.remove('search-jump-highlight');
                });
                
                // 添加新的高亮
                const highlights = document.querySelectorAll('.search-highlight');
                if (highlights[index]) {
                    highlights[index].classList.add('search-jump-highlight');
                    
                    // 滚动到视图
                    highlights[index].scrollIntoView({
                        behavior: 'smooth',
                        block: 'center'
                    });
                }
            }
            
            clearHighlights() {
                document.querySelectorAll('.search-highlight').forEach(highlight => {
                    const text = document.createTextNode(highlight.textContent);
                    highlight.parentNode.replaceChild(text, highlight);
                });
            }
        }
        
        // 初始化搜索组件
        new GlobalSearch();
    </script>
</body>
</html>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全局搜索组件</title>
    <style>
        /* 样式部分保持不变 */
    </style>
</head>
<body>
    <!-- HTML结构保持不变 -->
    
    <script>
        class GlobalSearch {
            // 构造函数和其他方法保持不变...
            
            performSearch() {
                const searchTerm = this.searchInput.value.trim();
                if (!searchTerm) {
                    this.clearResults();
                    this.removeHighlights();
                    return;
                }
                
                // 修复中文搜索问题的关键修改
                const escapedTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                // 添加u修饰符以支持Unicode字符(包括中文)
                const regex = new RegExp(escapedTerm, 'giu');
                
                // 其余搜索逻辑保持不变...
            }
            
            // 其他方法保持不变...
        }
        
        // 初始化保持不变...
    </script>
</body>
</html>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全局搜索组件</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #6366f1;
            --secondary: #8b5cf6;
            --dark: #1e293b;
            --light: #f8fafc;
            --glass: rgba(255, 255, 255, 0.1);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, #0f172a, #1e293b);
            color: var(--light);
            line-height: 1.6;
            padding: 20px;
        }

        .search-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            max-width: 400px;
            width: 90%;
        }

        .search-box {
            display: flex;
            background: var(--glass);
            border-radius: 50px;
            padding: 10px 20px;
            box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .search-input {
            flex: 1;
            background: transparent;
            border: none;
            outline: none;
            color: white;
            font-size: 16px;
            padding: 10px;
        }

        .search-btn {
            background: transparent;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 18px;
            padding: 0 10px;
        }

        .results-container {
            margin-top: 10px;
            background: var(--glass);
            border-radius: 10px;
            padding: 15px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            max-height: 300px;
            overflow-y: auto;
        }

        .result-item {
            padding: 12px;
            margin-bottom: 8px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 5px;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .result-item:hover {
            background: rgba(255, 255, 255, 0.1);
            transform: translateY(-2px);
        }

        .highlight {
            background-color: yellow;
            color: black;
            padding: 0 2px;
            border-radius: 2px;
        }

        .current-highlight {
            background-color: orange;
            animation: pulse 1s;
        }

        @keyframes pulse {
            0% { background-color: orange; }
            100% { background-color: yellow; }
        }

        @media (max-width: 768px) {
            .search-container {
                top: 10px;
                right: 10px;
            }
            
            .search-input {
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
    <div class="search-container">
        <div class="search-box">
            <input type="text" class="search-input" placeholder="搜索页面内容...">
            <button class="search-btn"><i class="fas fa-search"></i></button>
        </div>
        <div class="results-container" id="results"></div>
    </div>

    <script>
        class GlobalSearch {
            constructor() {
                this.searchInput = document.querySelector('.search-input');
                this.searchBtn = document.querySelector('.search-btn');
                this.resultsContainer = document.getElementById('results');
                this.matches = [];
                this.currentIndex = 0;
                this.highlightedElements = [];
                
                this.initEvents();
            }
            
            initEvents() {
                this.searchBtn.addEventListener('click', () => this.performSearch());
                this.searchInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') this.performSearch();
                });
            }
            
            performSearch() {
                const searchTerm = this.searchInput.value.trim();
                if (!searchTerm) {
                    this.clearResults();
                    this.removeHighlights();
                    return;
                }
                
                this.clearResults();
                this.removeHighlights();
                this.matches = [];
                
                // 使用TreeWalker遍历所有文本节点
                const walker = document.createTreeWalker(
                    document.body,
                    NodeFilter.SHOW_TEXT,
                    null,
                    false
                );
                
                let node;
                while (node = walker.nextNode()) {
                    if (node.nodeValue.trim() === '') continue;
                    
                    const regex = new RegExp(searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
                    let match;
                    while ((match = regex.exec(node.nodeValue)) !== null) {
                        this.matches.push({
                            node: node,
                            parent: node.parentNode,
                            index: match.index,
                            length: match[0].length,
                            text: node.nodeValue
                        });
                    }
                }
                
                this.displayResults();
                this.highlightMatches();
            }
            
            displayResults() {
                this.resultsContainer.innerHTML = '';
                
                if (this.matches.length === 0) {
                    this.resultsContainer.innerHTML = '<div class="result-item">未找到匹配结果</div>';
                    return;
                }
                
                this.matches.forEach((match, i) => {
                    const resultItem = document.createElement('div');
                    resultItem.className = 'result-item';
                    
                    // 获取上下文内容
                    const start = Math.max(0, match.index - 20);
                    const end = Math.min(match.text.length, match.index + match.length + 20);
                    let context = match.text.substring(start, end);
                    
                    if (start > 0) context = '...' + context;
                    if (end < match.text.length) context = context + '...';
                    
                    // 高亮匹配内容
                    const highlighted = context.replace(
                        new RegExp(this.searchInput.value.trim(), 'gi'),
                        match => `<span class="highlight">${match}</span>`
                    );
                    
                    resultItem.innerHTML = highlighted;
                    
                    // 点击跳转到匹配位置
                    resultItem.addEventListener('click', () => {
                        this.jumpToMatch(i);
                    });
                    
                    this.resultsContainer.appendChild(resultItem);
                });
            }
            
            highlightMatches() {
                this.highlightedElements = [];
                
                this.matches.forEach(match => {
                    const range = document.createRange();
                    range.setStart(match.node, match.index);
                    range.setEnd(match.node, match.index + match.length);
                    
                    const span = document.createElement('span');
                    span.className = 'highlight';
                    range.surroundContents(span);
                    
                    this.highlightedElements.push(span);
                });
            }
            
            jumpToMatch(index) {
                if (index < 0 || index >= this.highlightedElements.length) return;
                
                this.currentIndex = index;
                const highlight = this.highlightedElements[index];
                
                // 移除之前的高亮
                document.querySelectorAll('.current-highlight').forEach(el => {
                    el.classList.remove('current-highlight');
                });
                
                // 添加新的高亮
                highlight.classList.add('current-highlight');
                
                // 平滑滚动到视图
                highlight.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center'
                });
            }
            
            clearResults() {
                this.resultsContainer.innerHTML = '';
            }
            
            removeHighlights() {
                this.highlightedElements.forEach(highlight => {
                    const parent = highlight.parentNode;
                    parent.replaceChild(document.createTextNode(highlight.textContent), highlight);
                    parent.normalize();
                });
                
                this.highlightedElements = [];
            }
        }
        
        // 初始化全局搜索
        document.addEventListener('DOMContentLoaded', () => {
            new GlobalSearch();
        });
    </script>
</body>
</html>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全局搜索功能</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #6366f1;
            --secondary: #8b5cf6;
            --dark: #1e293b;
            --light: #f8fafc;
            --glass: rgba(255, 255, 255, 0.1);
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, #0f172a, #1e293b);
            color: var(--light);
            margin: 0;
            min-height: 100vh;
        }

        .search-container {
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
        }

        .search-box {
            display: flex;
            background: var(--glass);
            border-radius: 50px;
            padding: 10px 20px;
            box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .search-input {
            flex: 1;
            background: transparent;
            border: none;
            outline: none;
            color: white;
            font-size: 18px;
            padding: 10px;
        }

        .search-btn {
            background: transparent;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 20px;
            padding: 0 10px;
        }

        .results-container {
            margin-top: 30px;
            background: var(--glass);
            border-radius: 10px;
            padding: 20px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .result-item {
            padding: 15px;
            margin-bottom: 10px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 5px;
            transition: all 0.3s ease;
        }

        .result-item:hover {
            background: rgba(255, 255, 255, 0.1);
            transform: translateY(-2px);
        }

        .highlight {
            background-color: yellow;
            color: black;
            padding: 0 2px;
            border-radius: 2px;
        }
    </style>
</head>
<body>
    <div class="search-container">
        <div class="search-box">
            <input type="text" class="search-input" placeholder="搜索整个页面内容...">
            <button class="search-btn"><i class="fas fa-search"></i></button>
        </div>
        <div class="results-container" id="results">
            <!-- 搜索结果将在这里显示 -->
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.querySelector('.search-input');
            const searchBtn = document.querySelector('.search-btn');
            const resultsContainer = document.getElementById('results');
            
            // 页面所有文本内容
            const pageContent = document.body.innerText;
            
            searchBtn.addEventListener('click', performSearch);
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    performSearch();
                }
            });

            function performSearch() {
                const searchTerm = searchInput.value.trim();
                if (!searchTerm) return;

                // 清空之前的结果
                resultsContainer.innerHTML = '';
                
                // 创建正则表达式进行不区分大小写的全局搜索
                const regex = new RegExp(searchTerm, 'gi');
                let match;
                let resultCount = 0;
                
                // 在整个页面内容中搜索
                while ((match = regex.exec(pageContent)) !== null) {
                    resultCount++;
                    
                    // 获取匹配文本周围的上下文
                    const start = Math.max(0, match.index - 20);
                    const end = Math.min(pageContent.length, match.index + searchTerm.length + 20);
                    const context = pageContent.substring(start, end);
                    
                    // 高亮显示匹配的文本
                    const highlighted = context.replace(
                        new RegExp(searchTerm, 'gi'), 
                        match => `<span class="highlight">${match}</span>`
                    );
                    
                    // 创建结果项
                    const resultItem = document.createElement('div');
                    resultItem.className = 'result-item';
                    resultItem.innerHTML = `...${highlighted}...`;
                    resultsContainer.appendChild(resultItem);
                }
                
                // 如果没有找到结果
                if (resultCount === 0) {
                    resultsContainer.innerHTML = '<div class="result-item">没有找到匹配的结果</div>';
                }
            }
        });
    </script>
</body>
</html>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全局搜索组件</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #6366f1;
            --secondary: #8b5cf6;
            --dark: #1e293b;
            --light: #f8fafc;
            --glass: rgba(255, 255, 255, 0.1);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, #0f172a, #1e293b);
            color: var(--light);
            line-height: 1.6;
            padding: 20px;
        }

        .search-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            max-width: 400px;
            width: 90%;
        }

        .search-box {
            display: flex;
            background: var(--glass);
            border-radius: 50px;
            padding: 10px 20px;
            box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .search-input {
            flex: 1;
            background: transparent;
            border: none;
            outline: none;
            color: white;
            font-size: 16px;
            padding: 10px;
        }

        .search-btn {
            background: transparent;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 18px;
            padding: 0 10px;
        }

        .results-container {
            margin-top: 10px;
            background: var(--glass);
            border-radius: 10px;
            padding: 15px;
            backdrop-filter: blur(5px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            max-height: 300px;
            overflow-y: auto;
        }

        .result-item {
            padding: 12px;
            margin-bottom: 8px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 5px;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .result-item:hover {
            background: rgba(255, 255, 255, 0.1);
            transform: translateY(-2px);
        }

        .highlight {
            background-color: yellow;
            color: black;
            padding: 0 2px;
            border-radius: 2px;
        }

        .current-highlight {
            background-color: orange;
            animation: pulse 1s;
        }

        @keyframes pulse {
            0% { background-color: orange; }
            100% { background-color: yellow; }
        }

        @media (max-width: 768px) {
            .search-container {
                top: 10px;
                right: 10px;
            }
            
            .search-input {
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
    <div class="search-container">
        <div class="search-box">
            <input type="text" class="search-input" placeholder="搜索页面内容...">
            <button class="search-btn"><i class="fas fa-search"></i></button>
        </div>
        <div class="results-container" id="results"></div>
    </div>

    <script>
        class GlobalSearch {
            constructor() {
                this.searchInput = document.querySelector('.search-input');
                this.searchBtn = document.querySelector('.search-btn');
                this.resultsContainer = document.getElementById('results');
                this.matches = [];
                this.currentIndex = 0;
                this.highlightedElements = [];
                
                this.initEvents();
            }
            
            initEvents() {
                this.searchBtn.addEventListener('click', () => this.performSearch());
                this.searchInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') this.performSearch();
                });
            }
            
            performSearch() {
                const searchTerm = this.searchInput.value.trim();
                if (!searchTerm) {
                    this.clearResults();
                    this.removeHighlights();
                    return;
                }
                
                this.clearResults();
                this.removeHighlights();
                this.matches = [];
                
                // 使用TreeWalker遍历所有文本节点
                const walker = document.createTreeWalker(
                    document.body,
                    NodeFilter.SHOW_TEXT,
                    null,
                    false
                );
                
                let node;
                while (node = walker.nextNode()) {
                    if (node.nodeValue.trim() === '') continue;
                    
                    const regex = new RegExp(searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
                    let match;
                    while ((match = regex.exec(node.nodeValue)) !== null) {
                        this.matches.push({
                            node: node,
                            parent: node.parentNode,
                            index: match.index,
                            length: match[0].length,
                            text: node.nodeValue
                        });
                    }
                }
                
                this.displayResults();
                this.highlightMatches();
            }
            
            displayResults() {
                this.resultsContainer.innerHTML = '';
                
                if (this.matches.length === 0) {
                    this.resultsContainer.innerHTML = '<div class="result-item">未找到匹配结果</div>';
                    return;
                }
                
                this.matches.forEach((match, i) => {
                    const resultItem = document.createElement('div');
                    resultItem.className = 'result-item';
                    
                    // 获取上下文内容
                    const start = Math.max(0, match.index - 20);
                    const end = Math.min(match.text.length, match.index + match.length + 20);
                    let context = match.text.substring(start, end);
                    
                    if (start > 0) context = '...' + context;
                    if (end < match.text.length) context = context + '...';
                    
                    // 高亮匹配内容
                    const highlighted = context.replace(
                        new RegExp(this.searchInput.value.trim(), 'gi'),
                        match => `<span class="highlight">${match}</span>`
                    );
                    
                    resultItem.innerHTML = highlighted;
                    
                    // 点击跳转到匹配位置
                    resultItem.addEventListener('click', () => {
                        this.jumpToMatch(i);
                    });
                    
                    this.resultsContainer.appendChild(resultItem);
                });
            }
            
            highlightMatches() {
                this.highlightedElements = [];
                
                this.matches.forEach(match => {
                    const range = document.createRange();
                    range.setStart(match.node, match.index);
                    range.setEnd(match.node, match.index + match.length);
                    
                    const span = document.createElement('span');
                    span.className = 'highlight';
                    range.surroundContents(span);
                    
                    this.highlightedElements.push(span);
                });
            }
            
            jumpToMatch(index) {
                if (index < 0 || index >= this.highlightedElements.length) return;
                
                this.currentIndex = index;
                const highlight = this.highlightedElements[index];
                
                // 移除之前的高亮
                document.querySelectorAll('.current-highlight').forEach(el => {
                    el.classList.remove('current-highlight');
                });
                
                // 添加新的高亮
                highlight.classList.add('current-highlight');
                
                // 平滑滚动到视图
                highlight.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center'
                });
            }
            
            clearResults() {
                this.resultsContainer.innerHTML = '';
            }
            
            removeHighlights() {
                this.highlightedElements.forEach(highlight => {
                    const parent = highlight.parentNode;
                    parent.replaceChild(document.createTextNode(highlight.textContent), highlight);
                    parent.normalize();
                });
                
                this.highlightedElements = [];
            }
        }
        
        // 初始化全局搜索
        document.addEventListener('DOMContentLoaded', () => {
            new GlobalSearch();
        });
    </script>
</body>
</html>

推荐版本:全局搜索组件
实现悬浮按钮触发的全局搜索功能,美观不占空间
支持中英文、特殊字符和多词组搜索
搜索结果分组显示,点击自动跳转到页面位置
匹配内容高亮显示,当前选中项有特殊动画效果
完全响应式设计,适配移动设备和桌面端
优化搜索性能,使用防抖和TreeWalker高效遍历
智能上下文展示和结果分组,提升用户体验
支持ESC键关闭搜索框,点击外部区域自动关闭


<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <!--CNDKK-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全局搜索组件</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #6366f1;
            --secondary: #8b5cf6;
            --dark: #1e293b;
            --light: #f8fafc;
            --glass: rgba(255, 255, 255, 0.1);
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            line-height: 1.6;
            padding: 20px;
            min-height: 200vh; /* 测试滚动效果 */
        }

        .search-float-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            background: var(--primary);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            transition: all 0.3s ease;
        }

        .search-float-btn:hover {
            transform: scale(1.1);
            background: var(--secondary);
        }

        .search-container {
            position: fixed;
            bottom: 100px;
            right: 30px;
            width: 350px;
            max-width: 90vw;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            z-index: 1000;
            transform: translateY(20px);
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .search-container.active {
            transform: translateY(0);
            opacity: 1;
            visibility: visible;
        }

        .search-header {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: center;
        }

        .search-input {
            flex: 1;
            border: none;
            outline: none;
            font-size: 16px;
            padding: 10px;
        }

        .search-close {
            background: none;
            border: none;
            color: #999;
            font-size: 20px;
            cursor: pointer;
            margin-left: 10px;
        }

        .search-results {
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
        }

        .result-item {
            padding: 12px;
            margin-bottom: 8px;
            background: #f8f9fa;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .result-item:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }

        .highlight {
            background-color: #ffec99;
            color: #000;
            padding: 0 2px;
            border-radius: 2px;
        }

        .current-highlight {
            background-color: #ffc078;
            animation: pulse 1s;
        }

        @keyframes pulse {
            0% { background-color: #ffc078; }
            100% { background-color: #ffec99; }
        }

        .no-results {
            padding: 20px;
            text-align: center;
            color: #666;
        }

        @media (max-width: 768px) {
            .search-float-btn {
                bottom: 20px;
                right: 20px;
                width: 50px;
                height: 50px;
            }
            
            .search-container {
                bottom: 80px;
                right: 20px;
                width: calc(100vw - 40px);
            }
        }
    </style>
</head>
<body>
    <!-- 测试内容 -->
    <h1>全局搜索测试页面</h1>
    <p>这是一个测试页面,用于演示全局搜索功能。您可以搜索任意文本内容,包括中文、英文和特殊字符。</p>
    <p>搜索功能支持多词组匹配,点击搜索结果会自动跳转到页面中的对应位置。</p>
    <p>示例文本:HTML5、CSS3、JavaScript、响应式设计、移动优先、用户体验、交互设计</p>
    <p>另一个段落包含中文测试:前端开发、网页设计、用户界面、搜索功能、悬浮窗组件</p>

    <!-- 搜索悬浮按钮 -->
    <div class="search-float-btn" id="searchBtn">
        <i class="fas fa-search"></i>
    </div>

    <!-- 搜索容器 -->
    <div class="search-container" id="searchContainer">
        <div class="search-header">
            <input type="text" class="search-input" id="searchInput" placeholder="输入搜索内容...">
            <button class="search-close" id="searchClose">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="search-results" id="searchResults"></div>
    </div>

    <script>
        class GlobalSearch {
            constructor() {
                this.searchBtn = document.getElementById('searchBtn');
                this.searchContainer = document.getElementById('searchContainer');
                this.searchInput = document.getElementById('searchInput');
                this.searchClose = document.getElementById('searchClose');
                this.searchResults = document.getElementById('searchResults');
                this.matches = [];
                this.highlightedElements = [];
                this.currentIndex = 0;

                this.initEvents();
            }

            initEvents() {
                this.searchBtn.addEventListener('click', () => this.toggleSearch());
                this.searchClose.addEventListener('click', () => this.closeSearch());
                this.searchInput.addEventListener('input', () => this.debouncedSearch());
                document.addEventListener('click', (e) => {
                    if (!this.searchContainer.contains(e.target) && e.target !== this.searchBtn) {
                        this.closeSearch();
                    }
                });
            }

            toggleSearch() {
                this.searchContainer.classList.toggle('active');
                if (this.searchContainer.classList.contains('active')) {
                    this.searchInput.focus();
                }
            }

            closeSearch() {
                this.searchContainer.classList.remove('active');
                this.removeHighlights();
            }

            debouncedSearch() {
                clearTimeout(this.debounceTimer);
                this.debounceTimer = setTimeout(() => {
                    this.performSearch();
                }, 300);
            }

            performSearch() {
                const searchTerm = this.searchInput.value.trim();
                if (!searchTerm) {
                    this.clearResults();
                    this.removeHighlights();
                    return;
                }

                this.clearResults();
                this.removeHighlights();
                this.matches = [];

                // 支持多词组搜索
                const searchTerms = searchTerm.split(/\s+/).filter(term => term.length > 0);
                if (searchTerms.length === 0) return;

                // 创建包含所有搜索词的正则表达式
                const regexPattern = searchTerms.map(term => 
                    `(${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`
                ).join('|');
                
                const regex = new RegExp(regexPattern, 'giu');

                // 遍历所有文本节点
                const walker = document.createTreeWalker(
                    document.body,
                    NodeFilter.SHOW_TEXT,
                    {
                        acceptNode: function(node) {
                            // 跳过script、style等元素内的文本节点
                            if (node.parentNode.nodeName === 'SCRIPT' || 
                                node.parentNode.nodeName === 'STYLE' ||
                                node.parentNode.nodeName === 'NOSCRIPT') {
                                return NodeFilter.FILTER_REJECT;
                            }
                            return NodeFilter.FILTER_ACCEPT;
                        }
                    },
                    false
                );

                let node;
                while (node = walker.nextNode()) {
                    if (node.nodeValue.trim() === '') continue;

                    let match;
                    while ((match = regex.exec(node.nodeValue)) !== null) {
                        this.matches.push({
                            node: node,
                            parent: node.parentNode,
                            index: match.index,
                            length: match[0].length,
                            text: node.nodeValue,
                            matchText: match[0]
                        });
                    }
                }

                this.displayResults();
                this.highlightMatches();
            }

            displayResults() {
                this.searchResults.innerHTML = '';

                if (this.matches.length === 0) {
                    this.searchResults.innerHTML = '<div class="no-results">未找到匹配结果</div>';
                    return;
                }

                // 分组显示结果(按父元素分组)
                const groupedResults = this.groupResultsByParent();

                Object.entries(groupedResults).forEach(([parentId, matches], groupIndex) => {
                    const parentElement = document.querySelector(`[data-search-parent="${parentId}"]`);
                    if (!parentElement) return;

                    const groupHeader = document.createElement('div');
                    groupHeader.className = 'result-item group-header';
                    groupHeader.textContent = this.getParentDescription(parentElement);
                    groupHeader.style.fontWeight = 'bold';
                    groupHeader.style.backgroundColor = '#e9ecef';
                    this.searchResults.appendChild(groupHeader);

                    matches.forEach((match, matchIndex) => {
                        const globalIndex = this.matches.indexOf(match);
                        const resultItem = document.createElement('div');
                        resultItem.className = 'result-item';
                        
                        // 获取上下文内容
                        const start = Math.max(0, match.index - 20);
                        const end = Math.min(match.text.length, match.index + match.length + 20);
                        let context = match.text.substring(start, end);
                        
                        if (start > 0) context = '...' + context;
                        if (end < match.text.length) context = context + '...';

                        // 高亮所有匹配的词
                        const highlighted = context.replace(
                            new RegExp(this.matches[globalIndex].matchText, 'giu'),
                            matched => `<span class="highlight">${matched}</span>`
                        );

                        resultItem.innerHTML = highlighted;
                        resultItem.addEventListener('click', () => {
                            this.jumpToMatch(globalIndex);
                        });

                        this.searchResults.appendChild(resultItem);
                    });
                });
            }

            groupResultsByParent() {
                const groups = {};
                
                this.matches.forEach(match => {
                    // 为父元素添加唯一标识
                    if (!match.parent.hasAttribute('data-search-parent')) {
                        const parentId = 'parent-' + Math.random().toString(36).substr(2, 9);
                        match.parent.setAttribute('data-search-parent', parentId);
                    }
                    
                    const parentId = match.parent.getAttribute('data-search-parent');
                    
                    if (!groups[parentId]) {
                        groups[parentId] = [];
                    }
                    
                    groups[parentId].push(match);
                });
                
                return groups;
            }

            getParentDescription(parentElement) {
                // 尝试获取有意义的父元素描述
                if (parentElement.nodeName === 'P') return '段落文本';
                if (parentElement.nodeName === 'H1') return '标题';
                if (parentElement.nodeName === 'H2') return '二级标题';
                if (parentElement.nodeName === 'H3') return '三级标题';
                if (parentElement.nodeName === 'LI') return '列表项';
                if (parentElement.nodeName === 'DIV') return '内容区块';
                return '文本内容';
            }

            highlightMatches() {
                this.highlightedElements = [];
                
                this.matches.forEach(match => {
                    const range = document.createRange();
                    range.setStart(match.node, match.index);
                    range.setEnd(match.node, match.index + match.length);
                    
                    const span = document.createElement('span');
                    span.className = 'highlight';
                    range.surroundContents(span);
                    
                    this.highlightedElements.push(span);
                });
            }

            jumpToMatch(index) {
                if (index < 0 || index >= this.highlightedElements.length) return;
                
                this.currentIndex = index;
                const highlight = this.highlightedElements[index];
                
                // 移除之前的高亮
                document.querySelectorAll('.current-highlight').forEach(el => {
                    el.classList.remove('current-highlight');
                });
                
                // 添加新的高亮
                highlight.classList.add('current-highlight');
                
                // 平滑滚动到视图
                highlight.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center'
                });
                
                // 短暂聚焦后返回搜索框
                setTimeout(() => {
                    this.searchInput.focus();
                }, 1000);
            }

            clearResults() {
                this.searchResults.innerHTML = '';
            }

            removeHighlights() {
                this.highlightedElements.forEach(highlight => {
                    if (highlight.parentNode) {
                        const parent = highlight.parentNode;
                        parent.replaceChild(document.createTextNode(highlight.textContent), highlight);
                        parent.normalize();
                    }
                });
                
                this.highlightedElements = [];
                
                // 清理添加的父元素标识
                document.querySelectorAll('[data-search-parent]').forEach(el => {
                    el.removeAttribute('data-search-parent');
                });
            }
        }

        // 初始化全局搜索
        document.addEventListener('DOMContentLoaded', () => {
            new GlobalSearch();
        });
    </script>
</body>
</html>

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荻酷社区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值