马上就到双十一了,我们在京东淘宝购物,疯狂剁手的同时,有没有注意到京东的搜索框呢,除了能进行搜索内容以外,它的样式又是如何实现的呢?
下面就分析一下如何实现仿京东的搜索框。
核心分析:
JavaScript部分:
1、当文本框获取焦点的时候,div中的字体颜色变为rgb(200,200,200);
2、当文本框失去焦点事件发生时,div中的字体颜色变成原来的样式#989898;
3、当文本框输入内容时,div的属性变为 none,表现效果为文字消失;
4、当清除文本框里面内容时,divdiv的属性变为 inline-block,表现效果为文字消失;
因为是在文本框里面显示出来的内容,改变的是表单元素,判断文本框里面是否有输入内容,判断的依据是 表单的value值是否为 空字符串。
实现代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>仿京东搜索框</title> 6 <style> 7 *{ 8 margin: 0;padding:0; 9 } 10 .from{ 11 border:2px solid #e2231a; 12 width:490px; 13 height:36px; 14 position:relative; 15 margin:100px auto; 16 font-size: 12px; 17 18 } 19 .text{ 20 position:absolute; 21 line-height: 36px; 22 left:27px; 23 color:#989898; 24 z-index:-1; 25 } 26 .search{ 27 position:absolute; 28 left:22px; 29 width:430px; 30 height:34px; 31 outline:none; 32 border:1px solid transparent; 33 background:transparent; 34 line-height: 34px; 35 overflow: hidden; 36 37 } 38 .button{ 39 position:absolute; 40 right:0px; 41 width:58px; 42 height:36px; 43 background-color: #e2231a; 44 border:1px solid transparent; 45 margin:auto; 46 outline:none; 47 cursor: pointer; 48 } 49 button:hover{ 50 background-color: #c81623; 51 } 52 span img{ 53 position:absolute; 54 right:65px; 55 } 56 57 </style> 58 </head> 59 <div class='from'> 60 <div class='text'>暗夜游戏本</div> 61 <input type="text" class="search" value=''> 62 <span class='photo' title="未选择取任何文件"> 63 <img src="camera.png" alt=""> 64 </span> 65 <button class='button'> 66 <i><img src="search.png" alt=""></i> 67 </button> 68 </div> 69 <body> 70 <script> 71 var div = document.querySelector('.from'); 72 var input = document.querySelector('.search'); 73 var text = document.querySelector('.text'); 74 input.onfocus = function(){ 75 text.style.color = 'rgb(200,200,200)' 76 } 77 input.onblur = function(){ 78 text.style.color = '#989898' 79 } 80 input.oninput = function(){ 81 text.style.display = 'none'; 82 if (input.value == '') { 83 text.style.display = 'inline-block'; 84 }; } 85 </script> 86 </body> 87 </html>
显示效果:
1、未触发事件的状态
2、输入框里获取焦点的状态
3、输入框里输入内容
4、删除里面内容后
5、CSS样式效果(hover)