如何实现input聚焦时兄弟按钮右向左收缩消失、失焦时左向右展开?
实现搜索框聚焦时兄弟按钮的过渡动画效果
搞定这个交互效果很简单,咱们结合CSS过渡和JavaScript事件监听就能实现,具体步骤和代码如下:
核心思路
- 给按钮添加CSS过渡属性,保证动画平滑流畅
- 定义一个专门的收缩类,控制按钮的宽度、透明度等关键属性
- 通过监听搜索框的
focus(聚焦)和blur(失焦)事件,动态给按钮添加/移除收缩类
修改后的完整代码
CSS 样式
input[type=text] { width: 130px; box-sizing: border-box; border: 2px solid #ccc; border-radius: 25px; font-size: 16px; background-color: white; padding: 5px 0px 5px 10px; -webkit-transition: width 0.4s ease-in-out; transition: width 0.4s ease-in-out; right: 10px; position: fixed; } input[type=text]:focus { width: 96%; } .navbar { background: #fff; border: none; border-bottom-left-radius: 25px; border-bottom-right-radius: 25px; box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1); } /* 按钮基础过渡样式,和搜索框动画时长保持一致 */ #sidebarCollapse { -webkit-transition: all 0.4s ease-in-out; transition: all 0.4s ease-in-out; white-space: nowrap; /* 防止按钮文字换行 */ } /* 按钮收缩状态的类 */ #sidebarCollapse.collapsed { width: 0; opacity: 0; padding: 0; border: none; overflow: hidden; margin-left: -10px; /* 消除按钮收缩后留下的空白 */ }
HTML 结构
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet"/> <nav class="navbar navbar-expand-lg navbar-light fixed-top" style="background-color:#6d7fcc;"> <div class="container-fluid"> <button type="button" id="sidebarCollapse" class="btn btn-info"> <i class="fas fa-align-left"></i> <span>Table Of Contents</span> </button> <input type="text" name="search" placeholder="Search..."> </div> </nav>
JavaScript 交互逻辑
const searchInput = document.querySelector('input[name="search"]'); const sidebarBtn = document.getElementById('sidebarCollapse'); // 搜索框聚焦时,给按钮添加收缩类 searchInput.addEventListener('focus', () => { sidebarBtn.classList.add('collapsed'); }); // 搜索框失焦时,移除收缩类恢复按钮 searchInput.addEventListener('blur', () => { // 加个小延迟,避免点击按钮时出现动画闪烁 setTimeout(() => { sidebarBtn.classList.remove('collapsed'); }, 100); });
效果说明
- 当点击搜索框聚焦时,按钮会以右向左的过渡动画逐渐收缩至完全消失,和搜索框的宽度扩展动画同步
- 当点击页面其他区域让搜索框失焦时,按钮会以左向右的过渡动画重新展开恢复
- 加的100ms延迟是为了避免点击按钮本身时,搜索框失焦导致按钮先恢复再被点击的视觉闪烁问题
内容的提问来源于stack exchange,提问作者Muyie
相关产品推荐
相关产品推荐

