placeholder 是 HTML5 為輸入框加上提示文字的便利屬性,寫法極簡:
<input type="text" id="search" name="search" placeholder="請輸入關鍵字..." />
問題在於舊版瀏覽器完全不認這個屬性。下面的做法是先做能力偵測,不支援時再用 JavaScript 模擬相同的外觀與行為。
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>HTML5 placeholder 相容處理</title>
<style type="text/css">
.placeholder { color: #a9a9a9; }
</style>
<script src="jquery.js"></script>
<script type="text/javascript">
// 偵測瀏覽器是否原生支援 placeholder
(function () {
var inp = document.createElement("input");
window.supports = {
placeholder: "placeholder" in inp
};
})();
// 為不支援的環境綁定模擬行為
function bindPlaceholder(obj) {
var jqobj = $(obj), placeholder = jqobj.attr("placeholder");
if (jqobj.val() == "") {
jqobj.val(placeholder);
jqobj.addClass("placeholder");
}
jqobj.bind({
focus: function () {
if ($(this).val() == placeholder) {
$(this).removeClass("placeholder");
$(this).val("");
}
},
blur: function () {
if ($(this).val() == "") {
$(this).addClass("placeholder");
$(this).val(placeholder);
}
}
});
}
$(document).ready(function () {
if (!window.supports.placeholder) {
$("input[placeholder]").each(function () {
bindPlaceholder(this);
});
}
});
</script>
</head>
<body>
<label for="search">搜尋</label>:
<input type="text" id="search" name="search" placeholder="請輸入關鍵字..." />
<button>送出</button>
</body>
</html>
能力偵測而非版本判斷。用 "placeholder" in inp 檢查特性是否存在,比判斷瀏覽器版本可靠得多,也不需要在新版瀏覽器上跑多餘的程式。
用 class 區分提示狀態。模擬出來的提示文字只是普通 value,必須靠 .placeholder 這個 class 把它上色成灰色,視覺上才與原生行為一致。
記得處理表單送出。模擬方案最大的陷阱是:使用者什麼都沒填就送出,後端會收到一串提示文字。正式環境中應在 submit 事件中把等於提示文字的 value 清空,或改用能同時兼顧兩者的寫法。