<label class="input-wrap">
<span class="placeholder" onclick="FocusInput(this)">請輸入密碼</span>
<input type="password" id="pwd" onfocus="HidePlaceholder(this)" />
</label>
<style>
.input-wrap { position: relative; display: inline-block; }
.placeholder { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none; }
</style>
<script>
function HidePlaceholder(input) {
var span = input.previousElementSibling;
if (span && span.classList.contains('placeholder')) span.style.display = 'none';
}
function FocusInput(span) {
span.style.display = 'none';
span.nextElementSibling.focus();
}
</script>
缺點:瀏覽器自動填充會導致「重影」(提示文字與自動填充值重疊)。
<input type="text" class="with-hint" style="background: url(hint.png) no-repeat 10px center;" />
<style>
.with-hint:focus { background-image: none; }
</style>
缺點:IE7 不支援 :focus 偽類;需準備圖片資源;多語系需多張圖。
<input type="text" placeholder="請輸入帳號" />
<input type="password" placeholder="請輸入密碼" />
jquery.placeholder)。<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="0">
<!-- 或表單層級 -->
<form autocomplete="off">...</form>
<!-- 或單一 input -->
<input autocomplete="off" />
注意:現代瀏覽器為安全性常忽略 autocomplete="off",密碼欄位建議改用 autocomplete="new-password"。
| 方案 | 相容性 | 維護性 | 自動填充衝突 | 推薦場景 |
|---|---|---|---|---|
| Span 定位 | 全瀏覽器 | 需額外 JS/CSS | 嚴重 | 極舊專案維護 |
| 背景圖 | IE8+ | 圖片管理成本高 | 無 | 固定樣式、單語系 |
| placeholder | IE10+(Polyfill 可補) | 零成本、語意化 | 無 | **現代專案首選** |