需求
实现一个搜索框,正常状态下只显示一个搜索按钮图标,点击之后显示整个搜索框并自动获得焦点,再次点击变回小按钮


分析
flex布局:居中———>
由一个input和一个按钮组成,通过定位仅仅显示按钮,此时的搜索框的长度为按钮的长度
当点击按钮的时候,为容器样式添加一个类,输入框的长度发生变化,同时按钮向右移动,并自动获得焦点
当再次点击按钮的时候取消这个类
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
<!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="style.css" /> <title>Hidden Search</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="script.js"></script> </body> </html>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap'); *{ margin: 0; padding: 0; box-sizing: border-box; }
body{ background-image: linear-gradient(90deg, #7d5fff, #7158e2); font-family: 'Roboto', sans-serif; height: 100vh; display: flex; justify-content: center; align-items: center; overflow: hidden; }
.search{ height: 50px; position: relative; }
.search .input{ background-color: #fff; width: 50px; height: 50px; padding: 15px; font-size: 18px; border: 0; transition: width 0.3s ease; }
.search .btn{ height: 50px; width: 50px; border: 0; font-size: 24px; position: absolute; background-color: #fff; cursor: pointer; left: 0; top: 0; transition: transform 0.3s ease; }
.btn:focus, .input:focus{ outline: none; }
.search.active .input{ width: 200px; }
.search.active .btn{ transform: translateX(198px); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
let search = document.querySelector('.search') let btn = document.querySelector('.btn') let input = document.querySelector('.input')
btn.addEventListener('click', () => { search.classList.toggle('active') input.focus() })
|
总结
通过定位让按钮遮盖在输入框上,并截取输入框令其不显示,在点击按钮之后令图标进行平移即可


另外总结一下transition的用法
1 2 3 4 5 6 7 8 9 10 11 12 13
| transition: property duration timing-function delay /*以上是transition的四个属性 1.始终需要指定transition-duration属性,否则持续时间为0,transition不会有任何效果 2.property指定CSS属性,例如上述例子中指定的width 3.duration指需要指定多少时间才能完成,如上述例子中,如果输入框恢复的时间小于按钮移动的时间,那么在动画过程中可以看到短暂明显的间隙 4.transition-timing-function 可以指定转速曲线,可以选择以下属性: a)linear 以相同速度开始至结束 b)ease 慢速开始,然后变快,然后慢速结束 c)ease-in 慢速开始 d)ease-out 慢速结束 e)ease-in-out 慢速开始和结束 f)cubic-bezier(n,n,n,n) 自定义变速曲线 */
|