DAY4-隐藏展开搜索框
前言
这个项目来源于GitHub上的一个开源项目https://github.com/bradtraversy/50projects50days,总共有50个用来练手的前端项目,我学习然后复现效果,并记录学习笔记和心得。
效果展示
本案例可以通过点击搜索按钮,进行展开和隐藏搜索框,是个小巧的案例
代码实现
HTML&CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hidden-search-widget</title>
<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"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
padding: 0;
margin: 0;
}
body {
height: 100vh;
background-color: #7a5df7;
display: flex;
justify-content: center;
align-items: center;
}
.input-container {
height: 50px;
position: relative;
}
.input-container input {
height: 50px;
width: 50px;
box-sizing: border-box;
outline: none;
border: none;
padding: 15px;
font-size: 18px;
transition: width .5s ease;
}
.input-container input::placeholder {
font-size: 18px;
}
.input-container .search {
border: none;
width: 50px;
height: 50px;
background-color: #fff;
text-align: center;
font-size: 25px;
cursor: pointer;
position: absolute;
left: 0;
top: 0;
transition: transform .55s ease;
}
.input-container.active input{
width: 200px;
}
.input-container.active .search{
transform: translateX(200px);
}
</style>
</head>
<body>
<div class="input-container">
<input placeholder="Search..." type="text">
<button class="search"><i class="fa fa-search" aria-hidden="true"></i></button>
</div>
</body>
</html>
JS
let container = document.querySelector(".input-container");
let search = document.querySelector(".search");
let input = document.querySelector("input");
search.onclick = () => {
if (container.classList.contains('active')){
container.classList.remove('active')
}else {
input.focus()
container.classList.add('active')
}
}
技术要点
-
这个案例中不仅仅是只更改input的宽度,而且要改变button的位置,如果只改变input的宽度,整个输入框只会往一边收缩。达不到两边同时收缩的效果。
-
看了作者的js代码后,我发现了他用了一个方法
classList.toggle('active')
,很方便,这个方法可以给切换的方法添加移除类名,就不用像我上面的js那样写了,下面贴出作者的代码const search = document.querySelector('.search') const btn = document.querySelector('.btn') const input = document.querySelector('.input') btn.addEventListener('click', () => { search.classList.toggle('active') input.focus() })
DAY4-隐藏展开搜索框
https://www.zhaojun.inkhttps://www.zhaojun.ink/archives/day4-hidden-search-widget