HTML5 placeholder 屬性在 IE9 以下不支援。本文提供兩種 jQuery Polyfill 方案:原生 JS 實現(無依賴邏輯)與 jQuery 簡化版,均支援聚焦清空、失焦恢復、樣式區分,並自動檢測瀏覽器原生支援情況。
$(document).ready(function() {
var doc = document;
var inputs = doc.getElementsByTagName('input');
// 檢測原生支援
var supportPlaceholder = 'placeholder' in doc.createElement('input');
function placeholder(input) {
var text = input.getAttribute('placeholder');
var 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];
var text = input.getAttribute('placeholder');
if (input.type === 'text' && text) {
placeholder(input);
}
}
}
});
$(function() {
// 檢測原生支援
function placeholderSupport() {
return 'placeholder' in document.createElement('input');
}
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(); // 初始化觸發 blur 設置初始狀態
}
});
.placeholder {
color: #999; /* 模擬原生 placeholder 顏色 */
/* 可添加 italic 等樣式區分 */
}
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Placeholder Polyfill Demo</title>
<script src="js/jquery-1.4.2.min.js"></script>
<style>
.placeholder { color: #999; }
</style>
</head>
<body>
<form>
<label for="name">用戶名:</label>
<input type="text" placeholder="請輸入用戶名" />
</form>
</body>
</html>
| 維度 | 方案一(原生 JS) | 方案二(jQuery) |
|---|---|---|
| 代碼量 | 較多 | 精簡 |
| 依賴 | 僅 jQuery 核心 | jQuery 核心 |
| 性能 | 略優(無 jQuery 封裝開銷) | 現代瀏覽器無感知差異 |
| 維護性 | 較低 | 高(鏈式調用、語義清晰) |
| 擴展性 | 需手動擴展 | 易擴展(如密碼框、textarea) |
$('input[placeholder], textarea[placeholder]')type="text" → type="password" 切換(需克隆節點)submit 時移除值等於 placeholder 的字段$(document).on('focus', '[placeholder]', ...)placeholderSupport() 結果避免重複創建元素IE9+ 已原生支援。現代項目建議:
<!--[if lt IE 10]><script src="placeholder-polyfill.js"></script><![endif]-->Placeholders.js、jquery-placeholder