如何实现搜索输入框与按钮联动缩放且不干扰其他按钮布局?
实现搜索框缩放时其他按钮固定位置的方案
核心修改思路
- 将搜索容器设为
inline-block,使其和其他按钮处于同一行内流中 - 给搜索输入框设置更高的
z-index,确保缩放时能覆盖在其他按钮上方 - 搜索按钮改为绝对定位,以搜索容器为参考,始终固定在输入框右侧
- 调整输入框右侧内边距,避免搜索按钮遮挡输入内容
修改后的完整代码
CSS 代码
button { font-family: Arial Narrow, sans-serif; font-size: 20pt; } .search { display: inline-block; position: relative; /* 为绝对定位的搜索按钮提供定位参考 */ } .search input { font-family: Arial Narrow, sans-serif; font-size: 20pt; width: 160px; height: 42px; padding-left: 15px; padding-right: 50px; /* 预留搜索按钮的空间,防止输入内容被遮挡 */ border-radius: 42px; border: 2px solid #404040; background: #FFDFBF; outline: none; transition: .3s linear; position: relative; z-index: 1; /* 让输入框缩放时覆盖在其他按钮上方 */ } .search input:focus { width: 512px; } .search button { width: 42px; height: 42px; background: none; border: none; position: absolute; right: 0; /* 固定在搜索容器右侧 */ top: 0; cursor: pointer; }
HTML 代码
<DIV class="search"> <INPUT type=text name="q" placeholder="搜索..."> <BUTTON>🔎</BUTTON> </DIV> <BUTTON>Some other button...</BUTTON> <BUTTON>Some other button 2...</BUTTON>
效果说明
- 常规状态:搜索框与其他按钮在同一行,其他按钮位于搜索框右侧
- 输入框聚焦缩放:输入框宽度增加,覆盖在其他按钮上方,其他按钮位置保持不变
- 搜索按钮始终固定在输入框最右侧,不会随输入框宽度变化移位
内容的提问来源于stack exchange,提问作者user19613364
相关产品推荐
相关产品推荐

