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

如何让搜索与关闭SVG图标点击后处于同一位置?

解决方案

核心问题

  1. 两个按钮定位基准不统一:#openSearchButton 相对 <nav> 定位,#closeButton 相对 .search-container 定位,导致位置偏移
  2. #closeButton 的 right 属性设置为 0,与 #openSearchButton 的 right:92px 不匹配
  3. 部分CSS属性存在拼写错误(如 height:19%important; 应为 height:19%!important;)

具体修改代码

1. CSS 调整

/* 给导航栏添加相对定位,作为按钮的统一定位基准 */
.navbar {
  position: relative;
}

#openSearchButton,
#closeButton {
  padding: 6px!important;
  border: none!important;
  cursor: pointer!important;
  position: absolute!important;
  background-color: transparent!important;
  color: white!important;
  top: 60%!important;
  transform: translateY(-50%)!important;
  /* 统一两个按钮的右侧距离,确保位置完全重合 */
  right: 92px!important;
  display: flex!important;
  align-items: center!important;
  /* 提高层级,避免被搜索容器遮挡 */
  z-index: 100!important;
}

#openSearchButton:hover {
  color: #cccccc!important;
}

#openSearchButton svg {
  transition: color 0.2s ease-in-out!important;
}

#closeButton {
  display: none;
  color: white;
  /* 移除原有的right:0设置 */
}

/* 调整搜索容器层级,确保按钮在上方 */
.search-container {
  display: flex;
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 99!important;
}

#searchInput {
  flex-grow: 1;
  padding: 15px 145px;
  border: none;
  width: 100%;
  /* 修正!important的位置 */
  height: 19%!important;
  font-family: 'Poppins';
  font-size: 18px;
}

#searchForm {
  width: 100%;
  height: 75%!important;
  position: relative;
  display: unset;
}

#submitSearchButton {
  position: relative;
  cursor: pointer;
  top: -38px;
  right: -97px;
  border: none;
  background: none;
}

#openSearchButton svg {
  width: 1em;
  height: 1em;
}

#closeButton svg {
  width: 2.5em;
  height: 1em;
}

2. HTML 保持原结构即可

无需调整HTML层级,确保<nav>包含.search-container和#openSearchButton即可。

3. JavaScript 优化(可选)

用更简洁的逻辑控制显示隐藏:

const openSearchBtn = document.getElementById('openSearchButton');
const closeBtn = document.getElementById('closeButton');
const searchContainer = document.getElementById('searchContainer');
const searchForm = document.getElementById('searchForm');

openSearchBtn.addEventListener('click', () => {
  searchContainer.style.display = 'flex';
  openSearchBtn.style.display = 'none';
  closeBtn.style.display = 'block';
});

closeBtn.addEventListener('click', () => {
  searchContainer.style.display = 'none';
  closeBtn.style.display = 'none';
  openSearchBtn.style.display = 'block';
});

searchForm.addEventListener('submit', (e) => {
  const searchQuery = document.getElementById('searchInput').value.trim();
  if (!searchQuery) e.preventDefault();
});

修改后,搜索图标和关闭图标会在同一位置切换显示,点击时不会出现位置偏移问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:19:54