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

Bootstrap 5导航栏实现点击搜索图标显示下方搜索框的方法

解决方案

1. HTML 结构调整

在导航栏的登录按钮后添加搜索触发按钮和搜索框容器:

<!-- 导航栏部分 -->
<nav class="navbar">
  <!-- 保留你原有导航元素 -->
  <button class="login-btn">登录</button>
  <!-- 搜索触发按钮 -->
  <button class="search-trigger" aria-label="打开搜索框">
    <!-- 搜索图标(用SVG示例,可替换为字体图标) -->
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <circle cx="11" cy="11" r="8"></circle>
      <path d="m21 21-4.35-4.35"></path>
    </svg>
  </button>
</nav>

<!-- 搜索框容器,放在导航栏下方 -->
<div class="search-container">
  <input type="text" class="search-input" placeholder="搜索..." aria-label="搜索">
</div>

2. 核心 CSS 实现

用 :focus-within 伪类实现无JS交互,适配你的relative布局:

/* 保留你原有导航栏样式,新增以下规则 */
.navbar {
  position: relative;
  /* 你的透明背景、文字颜色等原有样式 */
}

.search-trigger {
  background: transparent;
  border: none;
  cursor: pointer;
  color: inherit;
  margin-left: 1rem;
}

/* 搜索容器默认隐藏 */
.search-container {
  display: none;
  position: relative;
  width: 100%;
  padding: 1rem;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 点击搜索按钮或搜索框获焦时显示容器 */
.navbar:focus-within + .search-container,
.search-container:focus-within {
  display: block;
}

.search-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

3. 可选:点击外部关闭搜索框

如果需要补充点击页面其他区域关闭搜索框的功能,仅需一行极简JS:

document.addEventListener('click', (e) => {
  const searchBox = document.querySelector('.search-container');
  const navbar = document.querySelector('.navbar');
  if (!navbar.contains(e.target) && !searchBox.contains(e.target)) {
    searchBox.style.display = 'none';
  }
});

说明

  • 用CSS伪类替代大量JS逻辑,最大限度减少代码量;
  • 搜索容器采用position: relative,与你的视频头布局保持一致,避免错乱;
  • 所有样式模块化,后续调整只需修改对应CSS类即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:51:17