在 HTML5 之前,輸入框提示文字需靠 JavaScript 監聽 focus/blur 切換 value 與樣式;HTML5 引入 placeholder 屬性後,原生支援無腳本提示,並自動處理語意、無障礙、表單驗證互動。本文對比兩種方案優劣、相容性、樣式客製化與最佳實務。
| 特性 | HTML5 placeholder | JS 傳統方案 (value+focus/blur) |
|---|---|---|
| 程式碼量 | 零 JS,單一屬性 | 需綁定事件、管理狀態 |
| 語意與無障礙 | 瀏覽器自動關聯 label、螢幕閱讀器可讀 | 需自行加 ARIA、隱藏真實 label |
| 表單驗證互動 | required 時 placeholder 不計為輸入值 | 需自行判斷是否為提示文字 |
| 樣式客製化 | ::placeholder 偽元素(現代瀏覽器) | 完全由 CSS 控制 .hint class |
| IE 相容性 | IE10+ 完整支援,IE9 不支援 | 全版本支援(含 IE6) |
| 密碼欄位 | 顯示明文提示,輸入時自動切換為密碼點 | 需手動切換 type 或雙 input 切換 |
| 提交行為 | 不會隨表單提交 | 若未清除會提交提示文字 |
<!-- 基礎用法 -->
<input type="text" name="search" placeholder="請輸入關鍵字">
<!-- 密碼欄位 -->
<input type="password" name="pwd" placeholder="至少 8 碼英數混合">
<!-- 多行文字 -->
<textarea name="bio" placeholder="介紹一下你自己..."></textarea>
<!-- 樣式客製化(現代瀏覽器) -->
<style>
::placeholder { color: #999; opacity: 1; font-style: italic; } /* 標準 */
::-webkit-input-placeholder { color: #999; } /* WebKit 舊版 */
::-moz-placeholder { color: #999; opacity: 1; } /* Firefox 19- */
:-ms-input-placeholder { color: #999; } /* IE10-11 */
</style>
<style>
.hint-input { border:1px solid #ccc; padding:8px 12px; font-size:14px; color:#333; }
.hint-input.placeholder { color:#999; font-style:italic; }
</style>
<input type="text" class="hint-input" value="請輸入關鍵字"
onfocus="if(this.value==='請輸入關鍵字'){this.value=''; this.classList.remove('placeholder');}"
onblur="if(this.value===''){this.value='請輸入關鍵字'; this.classList.add('placeholder');}">
<!-- 或集中管理版 -->
<script>
document.querySelectorAll('[data-placeholder]').forEach(el => {
const hint = el.dataset.placeholder;
el.value = hint; el.classList.add('placeholder');
el.addEventListener('focus', () => { if(el.value===hint){el.value=''; el.classList.remove('placeholder');} });
el.addEventListener('blur', () => { if(el.value===''){el.value=hint; el.classList.add('placeholder');} });
// 表單送出前清理
el.form?.addEventListener('submit', () => { if(el.value===hint) el.value=''; });
});
</script>
<!-- 1. 原生 placeholder -->
<input type="text" name="q" placeholder="搜尋內容...">
<!-- 2. 針對 IE9 載入輕量 Polyfill(如 placeholders.js 約 1KB gzip) -->
<!--[if lte IE 9]>
<script src="vendor/placeholders.min.js"></script>
<![endif]-->
input.placeholder = '新提示' 即時生效。<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="name@example.com" required>
螢幕閱讀器會讀出 "Email, edit text, placeholder name@example.com"。
:placeholder-shown 偽類(支援度佳)實現 Material Design 風格浮動標籤,無需 JS。
.floating-label { position:relative; }
.floating-label input { width:100%; padding:12px 0; border:none; border-bottom:1px solid #ccc; background:none; }
.floating-label label { position:absolute; top:12px; left:0; transition:0.2s; pointer-events:none; color:#999; }
.floating-label input:focus + label,
.floating-label input:not(:placeholder-shown) + label { top:-16px; font-size:12px; color:#3f51b5; }
結論:現代專案**直接使用 placeholder**,僅在必須支援 IE9 時載入極輕量 Polyfill,兼顧開發效率、無障礙、維護性與使用者體驗。