代码来自于github上的50projects50days,我加了一些注释
效果图展示Hidden Search Widget(可能需要科学上网)
话不多说直接上代码(代码中的图片url和网址之类的可能需要科学上网,如果没有的话可以考虑欢称自己的图片)
大部分解释都在代码注释中,可能会随着天数的增加而减少代码(因为记住了)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 引入图标 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="sha512-1PKOgIY59xJ8Co8+NE6FZ+LOAZKjy+KY8iq0G4B3CyeY6wYHN3yt9PW0XpSriVlkMXe40PTKnXrLnZ9+fkDaog==" crossorigin="anonymous" />
<link rel="stylesheet" href="index.css">
<title>隐藏搜索栏</title>
</head>
<body>
<div class="search">
<input type="text" class="input" placeholder="Search...">
<button class="btn">
<!-- 图标 -->
<i class="fas fa-search"></i>
</button>
</div>
<script src="index.js"></script>
</body>
</html>
css
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
* {
box-sizing: border-box;
}
body {
/* 渐变颜色 */
background-image: linear-gradient(90deg, #7d5fff, #7158e2);
font-family: 'Roboto', sans-serif;
/* 浮动类型 */
display: flex;
/* 交叉轴方向上的对齐方式 */
align-items: center;
/* justify-content 属性定义了浏览器之间,如何分配顺着弹性容器主轴 (或者网格行轴) 的元素之间及其周围的空间 */
justify-content: center;
/* 有了高度才能使Search栏居中 */
height: 100vh;
overflow: hidden;
margin: 0;
}
.search {
position: relative;
height: 50px;
}
.search .input {
background-color: #fff;
border: 0;
font-size: 18px;
padding: 15px;
height: 50px;
width: 50px;
/* 给width添加动画 */
transition: width 0.3s ease;
}
.btn {
background-color: #fff;
border: 0;
/* 鼠标小手 */
cursor: pointer;
font-size: 20px;
/* 子绝父相 */
position: absolute;
top: 0;
left: 0;
height: 50px;
width: 50px;
/* 给移动添加动画 */
transition: transform 0.3s ease;
}
.btn:focus,
.input:focus {
/* 取消鼠标悬停时的动作 */
outline: none;
}
/* .active 在js中添加 */
.search.active .input {
width: 200px;
}
.search.active .btn {
transform:translateX(198px) ;
}
js
const search = document.querySelector('.search')
const btn = document.querySelector('.btn')
const input = document.querySelector('.input')
btn.addEventListener('click', ()=> {
// classList.toggle('className')会给search元素添加和消除类
search.classList.toggle('active')
// Search聚焦
input.focus()
})