原理:開始讓輸入框和搜索按鈕大小及形狀一致,通過定位讓他倆重疊在一塊,然后給監聽按鈕點擊事件,點擊時增加對應的類名,讓輸入框變長,按鈕向右移動對應的距離
```
<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>
```
開始:
點擊后: