HTML5 placeholder 屬性提供輸入框提示文字,現代瀏覽器完美支持,但 IE9 及以下不支持。本文提供純 JS Polyfill 方案與密碼框特殊處理技巧。
<input type="text" placeholder="請輸入用戶名">
<textarea placeholder="請輸入留言內容..."></textarea>
現代瀏覽器:聚焦時提示消失,失焦空值時恢復,提示文字顏色可通過 ::placeholder 偽元素自定義。
/**
* Placeholder Polyfill for IE9-
* 用法: new PlaceholderPolyfill().init('input[placeholder], textarea[placeholder]');
*/
class PlaceholderPolyfill {
constructor() {
this.nativeSupport = 'placeholder' in document.createElement('input');
this.activeElements = new WeakMap(); // 記錄原始值與狀態
}
init(selector) {
if (this.nativeSupport) return; // 現代瀏覽器直接返回
const elements = document.querySelectorAll(selector);
elements.forEach(el => this.bind(el));
// 動態添加的元素支持 (MutationObserver)
if (window.MutationObserver) {
new MutationObserver(mutations => {
mutations.forEach(m => m.addedNodes.forEach(node => {
if (node.nodeType === 1) {
if (node.matches(selector)) this.bind(node);
node.querySelectorAll(selector).forEach(el => this.bind(el));
}
}));
}).observe(document.body, { childList: true, subtree: true });
}
}
bind(el) {
if (el._placeholderBound) return;
el._placeholderBound = true;
const placeholder = el.getAttribute('placeholder');
if (!placeholder) return;
// 初始狀態
if (!el.value) {
el.value = placeholder;
el.style.color = '#999';
this.activeElements.set(el, { isPlaceholder: true });
}
// 聚焦:清空提示
el.addEventListener('focus', () => {
const state = this.activeElements.get(el);
if (state?.isPlaceholder) {
el.value = '';
el.style.color = '';
this.activeElements.set(el, { isPlaceholder: false });
}
});
// 失焦:恢復提示
el.addEventListener('blur', () => {
if (!el.value) {
el.value = placeholder;
el.style.color = '#999';
this.activeElements.set(el, { isPlaceholder: true });
} else {
el.style.color = '';
this.activeElements.set(el, { isPlaceholder: false });
}
});
// 表單提交前清理佔位符值
const form = el.closest('form');
if (form && !form._placeholderSubmitBound) {
form._placeholderSubmitBound = true;
form.addEventListener('submit', () => {
this.activeElements.forEach((state, el) => {
if (state.isPlaceholder) el.value = '';
});
});
}
}
// 表單驗證前調用,確保提示值不被當作真實數據提交
clearAll(selector) {
document.querySelectorAll(selector).forEach(el => {
const state = this.activeElements.get(el);
if (state?.isPlaceholder) el.value = '';
});
}
}
// 初始化
document.addEventListener('DOMContentLoaded', () => {
new PlaceholderPolyfill().init('input[placeholder], textarea[placeholder]');
});
密碼框 type="password" 顯示為圓點,無法直接顯示 placeholder 明文。解決方案:雙輸入框切換。
<div class="pwd-wrapper" style="position: relative;">
<input type="text" id="pwd-placeholder" value="請輸入密碼"
style="color: #999;" autocomplete="off">
<input type="password" id="pwd-real" style="display: none;" autocomplete="current-password">
</div>
const pwdPlaceholder = document.getElementById('pwd-placeholder');
const pwdReal = document.getElementById('pwd-real');
pwdPlaceholder.addEventListener('focus', () => {
pwdPlaceholder.style.display = 'none';
pwdReal.style.display = 'block';
pwdReal.focus();
});
pwdReal.addEventListener('blur', () => {
if (!pwdReal.value.trim()) {
pwdReal.style.display = 'none';
pwdPlaceholder.style.display = 'block';
}
});
// 表單提交時確保真實值被提交
document.querySelector('form')?.addEventListener('submit', () => {
if (pwdPlaceholder.style.display !== 'none') {
pwdPlaceholder.disabled = true; // 防止提交佔位符值
}
});
/* 修改 placeholder 顏色 */
::placeholder { color: #999; opacity: 1; } /* Firefox 需 opacity:1 */
::-webkit-input-placeholder { color: #999; } /* WebKit/Blink */
:-ms-input-placeholder { color: #999; } /* IE10-11 */
::-ms-input-placeholder { color: #999; } /* Edge (舊版) */
/* 修改 placeholder 字體樣式 */
::placeholder { font-style: italic; font-size: 0.9em; }
<!--[if lt IE 10]><script src="placeholder-polyfill.js"></script><![endif]-->)placeholder **不是** <label> 替代品,必須提供關聯的 <label> 或 aria-label<input type="password" placeholder="...">