萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Input 提示文字三種實作方案對比:Span 定位、背景圖、HTML5 placeholder

方案一:Span 絕對定位覆蓋(傳統相容)

<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 偽類;需準備圖片資源;多語系需多張圖。

方案三:HTML5 placeholder(現代首選)

<input type="text" placeholder="請輸入帳號" />
<input type="password" placeholder="請輸入密碼" />
  • 原生支援、自動處理焦點/自動填充、多語系只需改文字。
  • IE10+ 完整支援;IE9- 需 Polyfill(如 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+圖片管理成本高無固定樣式、單語系
placeholderIE10+(Polyfill 可補)零成本、語意化無**現代專案首選**
copyright © 萬盛學電腦網 all rights reserved