演示地址
Hidden Search (50projects50days.com)
实现思路
先把搜索框和搜索按钮盒子大小设置成一样,搜索按钮绝对定位盖住搜索框。点击搜索按钮时展开搜索框,同时利用transform将搜索按钮从搜索框上面移开。
代码
html结构
<!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 href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.1.1/css/all.css" 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 {
/* 父元素相对定位 */
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;
/* 绝对定位 */
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() 方法从列表中删除一个给定的标记并返回false。 如果标记不存在,则添加标记并且函数返回true
search.classList.toggle('active')
input.focus()
})
参考资料:50 Projects 50 Days | Traversy Media
50 unique mini-projects to sharpen your HTML, CSS & JavaScript skills