原理:开始让输入框和搜索按钮大小及形状一致,通过定位让他俩重叠在一块,然后给监听按钮点击事件,点击时增加对应的类名,让输入框变长,按钮向右移动对应的距离
```
<div class="search">
<input type="text" name="" placeholder="搜索" class="input">
<button class="btn">搜索</button>
</div>
<style type="text/css">
*{
margin: 0;
padding:0;
box-sizing: border-box;
}
body{
background:linear-gradient(to top,#0ea2c9,#7713d4);
height: 100vh;
}
.search{
position: relative;
display: inline-block;
height: 40px;
margin: 100px;
}
.input{
position: relative;
width: 40px;
height: 40px;
border: none;
outline: none;
background: #fff;
font-size: 14px;
border-radius: 12px;
padding: 15px;
}
//按钮定位
.btn{
position: absolute;
width: 40px;
height: 40px;
left: 0;
top: 0;
background: #fff;
border: none;
border-radius: 12px;
}
//输入框激活时样式
.search.active .input{
width: 200px;
transition: all 0.5s ease;
border-radius: 12px 0 0 12px;
}
//按钮点击时样式
.search.active .btn{
transition: all 0.5s ease;
transform: translateX(200px);
border-radius: 0 12px 12px 0;
}
</style>
<script type="text/javascript">
let btn = document.querySelector('.btn');//获取按钮
//给按钮增加点击事件,添加‘active’类
btn.addEventListener('click',function(e){
console.log("222");
if(!this.parentNode.classList.contains('active')){
this.parentNode.classList.add('active');
this.parentNode.children[0].focus();
}
})
// btn.parentNode.children[0].addEventListener('blur',function(e){
// this.parentNode.classList.remove('active');
// })
</script>
```
开始:![](https://img.kancloud.cn/ed/20/ed2042f95915da1de7190bc723e4bba9_106x93.png)
点击后:![](https://img.kancloud.cn/3b/62/3b621ce187495849044fde567fd0232f_524x151.png)