仿京東搜索框實例


馬上就到雙十一了,我們在京東淘寶購物,瘋狂剁手的同時,有沒有注意到京東的搜索框呢,除了能進行搜索內容以外,它的樣式又是如何實現的呢?

下面就分析一下如何實現仿京東的搜索框。

核心分析:

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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM