早期網站常見的搜尋框,未輸入時會顯示灰色的「請輸入關鍵字」,點進去就清空,離開時若還是空的就把提示放回去。這份範例用 onfocus 與 onblur 兩個事件就能完成。
function iniEvent() {
var txtSearch = document.getElementById("txtSearch");
txtSearch.onfocus = function () {
if (this.value == "請輸入關鍵字" || this.value == "") {
this.value = "";
this.style.color = "black";
}
};
txtSearch.onblur = function () {
if (this.value == "請輸入關鍵字" || this.value == "") {
this.value = "請輸入關鍵字";
this.style.color = "red";
} else {
this.style.color = "black";
}
};
}
<body onload="iniEvent()"> 查找<input type="text" id="txtSearch" value="請輸入關鍵字" style="color:red" /><br /> <input type="text" /> </body>
把提示文字寫進 value 有幾個明顯缺點。使用者若真的想搜尋「請輸入關鍵字」這五個字,會被程式清掉。表單提交時,若使用者沒點過輸入框,這個提示字串就會被當成搜尋條件送到後端。而且螢幕閱讀器會把它當成實際內容朗讀,造成混淆。
HTML5 的 placeholder 屬性天生就是為此設計,瀏覽器會自動處理聚焦隱藏、失焦還原,且不會被提交:
<input type="search" id="txtSearch" placeholder="請輸入關鍵字" />
若需要更精細的控制(例如自訂顏色或加上搜尋圖示),用 CSS 的 ::placeholder 偽元素即可:
#txtSearch::placeholder { color: #999; }
#txtSearch:focus::placeholder { color: transparent; }
需要提醒的是,placeholder 只能當作提示,不能取代 <label>。為輸入框加上標籤(可用 aria-label 或視覺隱藏的 label),才是兼顧無障礙與可用性的做法。