演示地址
Hidden Search (50projects50days.com)
實(shí)現(xiàn)思路
先把搜索框和搜索按鈕盒子大小設(shè)置成一樣,搜索按鈕絕對(duì)定位蓋住搜索框。點(diǎn)擊搜索按鈕時(shí)展開搜索框,同時(shí)利用transform將搜索按鈕從搜索框上面移開。
代碼
html結(jié)構(gòu)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>隱藏搜索小部件</title>
<link rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="search">
<input type="text" class="input" name="" placeholder="Search...">
<button class="btn">
<i class="fas fa-search"></i>
</button>
</div>
<script src="./script.js"></script>
</body>
</html>
css樣式
* {
box-sizing: border-box;
}
body {
/* 彈性布局,垂直居中 */
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: pink;
overflow: hidden;
}
.search {
/* 父元素相對(duì)定位 */
position: relative;
height: 50px;
}
.search .input {
padding: 15px;
height: 50px;
width: 50px;
border: 0;
background-color: #fff;
font-size: 18px;
transition: width 0.3s ease;
}
.btn {
cursor: pointer;
/* 絕對(duì)定位 */
position: absolute;
top: 0;
left: 0;
width: 50px;
height: 50px;
border: 0;
background-color: #fff;
font-size: 24px;
transition: transform 0.3s ease;
}
.btn:focus,
.input:focus {
outline: none;
}
.search.active .input {
width: 200px;
}
.search.active .btn {
transform: translateX(200px);
}
js行為
const search = document.querySelector('.search')
const btn = document.querySelector('.btn')
const input = document.querySelector('.input')
btn.addEventListener('click', () => {
// toggle() 方法從列表中刪除一個(gè)給定的標(biāo)記并返回false。 如果標(biāo)記不存在,則添加標(biāo)記并且函數(shù)返回true
search.classList.toggle('active')
input.focus()
})
參考資料:50 Projects 50 Days | Traversy Media
50 unique mini-projects to sharpen your HTML, CSS & JavaScript skills