Javascript:仿淘寶搜索框用戶輸入事件的實現


打開淘寶網首頁,找到淘寶首頁的搜索框,大家可以看到,當頁面一打開,搜索框中就可以看到灰色字體“少女高跟鞋”,還有閃爍的光標。當用戶點擊輸入的時候,灰色字消失。當用戶清空文本框的所有內容的時候,灰色字自動恢復。

接下來,這個小案例就是要介紹如何實現這種效果,即用戶輸入事件。

判斷用戶輸入的事件有 oninput 和onpropertychange 。當然,想必你能想到,由於瀏覽器兼容的問題,他們出現的場合有所不同。 正常瀏覽器支持oninput ,而 IE6、IE7、IE8 支持的 onpropertychange 。

為了節省時間,不再模仿淘寶CSS樣式。

代碼及解析 :

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>判斷用戶輸入事件第2遍oninput 和onpropertychange 的用法</title>
 6 </head>
 7  <style>
 8         .search {
 9             width:300px;
10             height: 30px;
11             margin: 100px auto;
12             position: relative;
13         }
14         .search input {
15             width:200px;
16             height:25px;
17 
18         }
19         .search label {
20             font-size: 12px;
21             color:#ccc;
22             position: absolute;
23             top:8px;
24             left:10px;
25             cursor: text;
26         }
27     </style>
28     <script type="text/javascript">
29     業務邏輯分析:
30 //           1.內容為空時,光標和默認字顯示在搜索框。自動獲取焦點
31 //           2.當輸入內容時,默認字消失。用oninput事件
32 
33         window.onload = function () {
34             function $(id){ return document.getElementById(id);}
35             $("txt").focus();//自動獲取光標方法
36             $("txt").oninput = $("txt").onpropertychange = function () {
37             //oninput 大部分瀏覽器支持  檢測用戶表單輸入內容
38             //onpropertychange  ie678  檢測用戶表單輸入內容
39                 if ( this.value == ""){
40                     // 首先判斷文本框里的值是否為空。注意用雙等號!
41                     $("message").style.display = "block";
42                 } else {
43                     $("message").style.display = "none";
44                 }
45             }
46         }
47     </script>  
48 <body>
49 <div class="search">
50     <input type="text" id="txt">
51     <label for="txt" id="message">仿淘寶搜索框</label>
52     <!-- 注意label 中for屬性 值指向 input 的id值 ,意思是把label標簽和input表單相關聯。
53     label 元素不會向用戶呈現任何特殊效果。當用戶在label元素內點擊文本, 瀏覽器就會自動將焦點轉到和標簽相關聯的表單控件上。 -->
54 </div>
55 </body>
56 </html>

 


免責聲明!

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



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