DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> js+css實現增加表單可用性之提示文字
js+css實現增加表單可用性之提示文字
編輯:關於JavaScript     
平常設計表單的時候,我們會加入一些提示文字,比如說在搜索框裡,我們會提示“請輸入關鍵字”,並在搜索框得到焦點和失去焦點的時候適時的隱藏和顯示,最常見的做法是利用value來設置:
復制代碼 代碼如下:
<form id="search">
<input type="text" id="keyword" name="keyword" value="請輸入關鍵字">
<button>搜索</button>
</form>
<script>
document.getElementById("keyword").onfocus = function() {
if (document.getElementById("keyword").value == "請輸入關鍵字") {
document.getElementById("keyword").value = "";
}
}
document.getElementById("keyword").onblur = function() {
if (document.getElementById("keyword").value == "") {
document.getElementById("keyword").value = "請輸入關鍵字";
}
}
document.getElementById("search").onsubmit = function() {
var keyword = document.getElementById("keyword").value;
if (keyword == "" || keyword == "請輸入關鍵字") {
alert("請輸入關鍵字");
return false;
}
return true;
}
</script>

如此的代碼雖然實現了我們要的功能,但卻不干淨,原因在於“請輸入關鍵字”這樣的文本僅僅是提示文字而已,而不是value,雖然技術上沒有大問題,但很多時候還是顯得麻煩,比如說我們可能像讓提示文字顯示的顏色是灰色,而用戶鍵入的文本則顯示黑色。
下面看看如何利用css來實現更好的方式:
復制代碼 代碼如下:
<style>
#wrapper { position: relative; display: inline; }
#description { position: absolute; left: 1px; color: #999999; display: none; }
</style>
<form id="search">
<div id="wrapper">
<label for="keyword" id="description">請輸入關鍵字</label>
<input type="text" id="keyword" name="keyword">
</div>
<button>搜索</button>
</form>
<script>
window.onload = function() {
if (!document.getElementById("keyword").value) {
document.getElementById("description").style.display = "inline";
}
};
document.getElementById("keyword").onfocus = function() {
if (!document.getElementById("keyword").value) {
document.getElementById("description").style.display = "none";
}
}
document.getElementById("keyword").onblur = function() {
if (!document.getElementById("keyword").value) {
document.getElementById("description").style.display = "inline";
}
}
document.getElementById("search").onsubmit = function() {
if (!document.getElementById("keyword").value) {
alert("請輸入關鍵字");
return false;
}
return true;
}
</script>

這樣的實現方式雖然CSS,JS代碼都多了一些,但是結構更合理,通過引入label來顯示提示文字(通過CSS的position屬性定位),讓value本身更單純,而且提示文字和用戶輸入的文本在樣式更容易控制,比如顏色的深淺,從而提高表單可用性。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved