如何让搜索与关闭SVG图标点击后处于同一位置?
解决方案
核心问题
- 两个按钮定位基准不统一:
#openSearchButton相对<nav>定位,#closeButton相对.search-container定位,导致位置偏移 #closeButton的right属性设置为0,与#openSearchButton的right:92px不匹配- 部分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
相关产品推荐
相关产品推荐

