Skip to content

Commit

Permalink
feat(search): 添加全站搜索功能
Browse files Browse the repository at this point in the history
- 在页面头部加入搜索框
- 实现文章、产品和关于我们内容的实时搜索
- 添加 cmd+k 快捷键触发搜索框聚焦
- 优化搜索框样式和布局
  • Loading branch information
chiimagnus committed Nov 20, 2024
1 parent 6bfdf02 commit 1cd4872
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
13 changes: 13 additions & 0 deletions css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -720,4 +720,17 @@ footer {
/* 折叠状态下隐藏多余的文章 */
#articlesList.collapsed article:nth-child(n+3) {
display: none;
}

.search-container {
margin-top: 20px;
padding: 10px;
}

#searchInput {
width: 100%;
padding: 8px;
border-radius: 4px;
border: 1px solid var(--border-color);
font-size: 1rem;
}
3 changes: 3 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ <h2 class="blog-title">Chii Magnus的博客</h2>
</li>
</ul>
</nav>
<div class="search-container">
<input type="text" id="searchInput" placeholder="搜索(快捷键cmd+k)" />
</div>
</aside>

<!-- 主内容区 -->
Expand Down
36 changes: 36 additions & 0 deletions js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,42 @@ document.addEventListener('DOMContentLoaded', () => {
});
});
}

const searchInput = document.getElementById('searchInput');

// 快捷键 cmd+k 触发搜索框聚焦
document.addEventListener('keydown', (e) => {
if (e.metaKey && e.key === 'k') {
e.preventDefault();
searchInput.focus();
}
});

// 搜索功能
searchInput.addEventListener('input', (e) => {
const query = e.target.value.toLowerCase();
const articles = document.querySelectorAll('.article-preview');
const products = document.querySelectorAll('.product-card');
const about = document.querySelector('.about-content');

// 搜索文章
articles.forEach(article => {
const text = article.textContent.toLowerCase();
article.style.display = text.includes(query) ? 'block' : 'none';
});

// 搜索产品
products.forEach(product => {
const text = product.textContent.toLowerCase();
product.style.display = text.includes(query) ? 'block' : 'none';
});

// 搜索关于我
if (about) {
const text = about.textContent.toLowerCase();
about.style.display = text.includes(query) ? 'block' : 'none';
}
});
});

async function loadArticles() {
Expand Down

0 comments on commit 1cd4872

Please sign in to comment.