placeholder 屬性讓輸入框能顯示提示文字,但 IE9 以下完全不支援。以下提供兩種補救方案,都是先偵測能力,不支援時才介入。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>placeholder 相容處理</title>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
// 第一種方法:原生 DOM 操作
$(document).ready(function () {
var doc = document,
inputs = doc.getElementsByTagName('input'),
supportPlaceholder = 'placeholder' in doc.createElement('input');
var placeholder = function (input) {
var text = input.getAttribute('placeholder'),
defaultValue = input.defaultValue;
if (defaultValue == '') {
input.value = text;
}
input.onfocus = function () {
if (input.value === text) { this.value = ''; }
};
input.onblur = function () {
if (input.value === '') { this.value = text; }
};
};
if (!supportPlaceholder) {
for (var i = 0, len = inputs.length; i < len; i++) {
var input = inputs[i], text = input.getAttribute('placeholder');
if (input.type === 'text' && text) { placeholder(input); }
}
}
});
// 第二種方法:純 jQuery 寫法
$(function () {
if (!placeholderSupport()) {
$('[placeholder]').focus(function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function () {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
}
});
function placeholderSupport() {
return 'placeholder' in document.createElement('input');
}
</script>
</head>
<body>
<form>
<label for="name">用戶名:</label>
<input type="text" id="name" placeholder="請輸入用戶名" />
</form>
</body>
</html>
第一種直接操作原生 DOM 與事件屬性,不依賴 jQuery 的選擇器引擎;第二種用 jQuery 串起 focus/blur,並透過加上 placeholder class 讓設計師能用 CSS 調整提示樣式(例如變成灰色斜體),視覺效果更可控。
兩者共同的關鍵都是那句能力偵測:'placeholder' in document.createElement('input')。這比判斷瀏覽器版本可靠得多,因為它問的是「這個環境支不支援」,而不是「這是什麼瀏覽器」。
type="password" 會把提示文字顯示成圓點。常見解法是額外放一個文字層疊在上面,取得焦點時隱藏並聚焦密碼欄。<label>,placeholder 只能當補充說明。今天若真要處理舊瀏覽器,比較好的做法是引入一個專門的 polyfill,而不是自己維護:
<script src="https://cdn.jsdelivr.net/npm/placeholders"></script>
或者用 CSS 幫原生 placeholder 上色,這在支援的瀏覽器中效果最好:
input::placeholder { color: #999; opacity: 1; }
input::-webkit-input-placeholder { color: #999; }
至於要不要為 IE8 以下的瀏覽器寫相容程式,取決於你的使用者統計——多數專案在這些環境的佔比已低到不值得投入。