萬盛學電腦網

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

JavaScript 實作輸入框預設提示文字(Placeholder Polyfill)

原生 placeholder 屬性(現代標準)

HTML5 原生支援 placeholder,無需 JavaScript:

<input type="text" placeholder="請輸入姓名" />
<input type="email" placeholder="請輸入電子郵件" />
<textarea placeholder="請輸入留言內容"></textarea>

優點:零 JS 依賴、無障礙支援完善、效能最佳、自動處理多語言、密碼欄位自動隱藏提示。

舊瀏覽器 Polyfill 實作(IE9-、舊版 WebView)

核心邏輯

  1. 讀取所有 input[placeholder]、textarea[placeholder]
  2. 儲存原始 placeholder 值
  3. focus 時:若值等於 placeholder → 清空、切換樣式
  4. blur 時:若值為空 → 恢復 placeholder、恢復樣式
  5. 表單提交前:清理所有 placeholder 值,避免提交到後端

完整 Polyfill 代碼

(function() {
  // 不支援 placeholder 才執行
  if ("placeholder" in document.createElement("input")) return;
  
  var inputs = document.querySelectorAll("input[placeholder], textarea[placeholder]");
  var stored = new WeakMap(); // 儲存原始 placeholder
  
  inputs.forEach(function(el) {
    var placeholder = el.getAttribute("placeholder");
    stored.set(el, placeholder);
    
    // 初始狀態:值為空時顯示提示
    if (!el.value) {
      el.value = placeholder;
      el.classList.add("placeholder-visible");
    }
    
    // 密碼欄位特殊處理:切換 type
    var isPassword = el.type === "password";
    var originalType = el.type;
    
    el.addEventListener("focus", function() {
      if (el.value === stored.get(el)) {
        el.value = "";
        el.classList.remove("placeholder-visible");
        if (isPassword) el.type = "password"; // 切換為真實密碼模式
      }
    });
    
    el.addEventListener("blur", function() {
      if (!el.value) {
        el.value = stored.get(el);
        el.classList.add("placeholder-visible");
        if (isPassword) el.type = "text"; // 切回明文顯示提示
      }
    });
  });
  
  // 表單提交前清理
  document.addEventListener("submit", function(e) {
    var form = e.target;
    inputs.forEach(function(el) {
      if (el.form === form && el.value === stored.get(el)) {
        el.value = "";
      }
    });
  }, true); // 捕獲階段優先執行
})();

配合 CSS 樣式

.placeholder-visible {
  color: #999 !important;      // 淺灰色區分
  font-style: italic;          // 斜體區分
  opacity: 0.7;
}

/* 現代瀏覽器原生 placeholder 樣式 */
::placeholder { color: #999; opacity: 1; }
::-webkit-input-placeholder { color: #999; }
::-moz-placeholder { color: #999; opacity: 1; }
:-ms-input-placeholder { color: #999; }

進階功能增強

浮動標籤效果

<div class="float-label">
  <input type="text" id="name" placeholder=" "> <!-- 空白佔位 -->
  <label for="name">姓名</label>
</div>

<style>
.float-label { position: relative; }
.float-label input { width: 100%; padding: 12px 0; border: none; border-bottom: 1px solid #ccc; }
.float-label label {
  position: absolute; top: 12px; left: 0;
  pointer-events: none; transition: 0.2s; color: #999;
}
.float-label input:focus + label,
.float-label input:not(:placeholder-shown) + label {
  top: -16px; font-size: 12px; color: #3498db;
}
</style>

字數統計與即時驗證

<textarea id="bio" placeholder="自我介紹 (最多 200 字)" maxlength="200"></textarea>
<div class="char-count"><span id="current">0</span>/200</div>

<script>
const textarea = document.getElementById("bio");
const counter = document.getElementById("current");

textarea.addEventListener("input", function() {
  counter.textContent = this.value.length;
  this.classList.toggle("over-limit", this.value.length > 200);
});
</script>

常見坑點與解決方案

問題原因解決
提交表單時 placeholder 值被送出Polyfill 未在 submit 前清理在 form.submit 事件中清空等於 placeholder 的值
密碼欄位顯示明文提示type="password" 不顯示文字focus 時切 type="password",blur 時切 type="text"(注意:部分舊瀏覽器不支援動態改 type)
自動填入時提示不消失瀏覽器自動填入不觸發 focus 事件使用 animationstart 偵測 autofill、或輪詢檢查 :-webkit-autofill
多語言切換提示不更新Polyfill 快取舊值語言切換時重新掃描 placeholder 屬性並更新 WeakMap

現代最佳實踐建議

  1. 優先使用原生 placeholder:所有現代瀏覽器(含 IE10+)完整支援
  2. 僅在必須支援 IE9 以下時載入 Polyfill(條件註釋或動態判斷)
  3. 不要用 value 模擬 placeholder:語意錯誤、無障礙差、提交污染
  4. 搭配 label 元素:Placeholder 非標籤替代品,螢幕閱讀器需 <label>
  5. 樣式統一:使用 ::placeholder 偽元素,避免 JS 操作樣式

總結

輸入框提示文字是表單易用性的關鍵細節。現代開發應優先使用原生 placeholder 屬性,僅在維護極舊環境時才考慮 Polyfill。若需更豐富互動(浮動標籤、字數統計、即時驗證),建議採用「Label + Input」結構配合 CSS :placeholder-shown、:focus、:valid/:invalid 偽類,實現零 JavaScript 的純 CSS 互動效果。

copyright © 萬盛學電腦網 all rights reserved