增加表單可用性之提示文字

來源:互聯網
上載者:User

平常設計表單的時候,我們會加入一些提示文字,比如說在搜尋方塊裡,我們會提示“請輸入關鍵字”,並在搜尋方塊得到焦點和失去焦點的時候適時的隱藏和顯示,最常見的做法是利用value來設定:

代碼(at pastebin.com):

01 <form id="search">
02 <input type="text" id="keyword" name="keyword" value="請輸入關鍵字">
03 <button>搜尋</button>
04 </form>
05
06 <script>
07 document.getElementById("keyword").onfocus = function() {
08     if (document.getElementById("keyword").value == "請輸入關鍵字") {
09         document.getElementById("keyword").value = "";
10     }
11 }
12 document.getElementById("keyword").onblur = function() {
13     if (document.getElementById("keyword").value == "") {
14         document.getElementById("keyword").value = "請輸入關鍵字";
15     }
16 }
17 document.getElementById("search").onsubmit = function() {
18     var keyword = document.getElementById("keyword").value;
19     if (keyword == "" || keyword == "請輸入關鍵字") {
20         alert("請輸入關鍵字");
21         return false;
22     }
23     return true;
24 }
25 </script>

如此的代碼雖然實現了我們要的功能,但卻不乾淨,原因在於“請輸入關鍵字”這樣的文本僅僅是提示文字而已,而不是value,雖然技術上沒有大問題,但很多時候還是顯得麻煩,比如說我們可能像讓提示文字顯示的顏色是灰色,而使用者鍵入的文字則顯示黑色。

下面看看如何利用css來實現更好的方式:

代碼(at pastebin.com):

01 <style>
02 #wrapper { position: relative; display: inline; }
03 #description { position: absolute; left: 1px; color: #999999; display: none; }
04 </style>
05
06 <form id="search">
07 <div id="wrapper">
08 <label for="keyword" id="description">請輸入關鍵字</label>
09 <input type="text" id="keyword" name="keyword">
10 </div>
11 <button>搜尋</button>
12 </form>
13
14 <script>
15 window.onload = function() {
16     if (!document.getElementById("keyword").value) {
17         document.getElementById("description").style.display = "inline";
18     }
19 };
20 document.getElementById("keyword").onfocus = function() {
21     if (!document.getElementById("keyword").value) {
22         document.getElementById("description").style.display = "none";
23     }
24 }
25 document.getElementById("keyword").onblur = function() {
26     if (!document.getElementById("keyword").value) {
27         document.getElementById("description").style.display = "inline";
28     }
29 }
30 document.getElementById("search").onsubmit = function() {
31     if (!document.getElementById("keyword").value) {
32         alert("請輸入關鍵字");
33         return false;
34     }
35     return true;
36 }
37 </script>

這樣的實現方式雖然CSS,JS代碼都多了一些,但是結構更合理,通過引入label來顯示提示文字(通過CSS的position屬性定位),讓value本身更單純,而且提示文字和使用者輸入的文本在樣式更容易控制,比如顏色的深淺,從而提高表單可用性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.