萬盛學電腦網

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

輸入框聚焦清除預設文字:Placeholder 現代寫法與舊版相容方案

「聚焦清除預設文字、失焦恢復」是經典表單交互模式。現代瀏覽器原生支援 placeholder 屬性,但舊專案仍需 JavaScript 實作。本文對比新舊方案,提供完整的漸進式增強策略。

現代標準:HTML5 placeholder (零 JS)

<input type="text" 
       id="search" 
       placeholder="請輸入關鍵字搜尋..." 
       class="search-input" />

<style>
  .search-input { padding: 10px 16px; border: 1px solid #ddd; border-radius: 4px; width: 300px; }
  /* 自訂 placeholder 樣式 */
  .search-input::placeholder { color: #999; font-style: italic; }
  .search-input:focus::placeholder { color: #ccc; opacity: 0.8; } /* 聚焦時淡出 */
</style>

優點: 零依賴、效能最佳、原生無障礙支援、語意正確。
缺點: IE9 以下不支援、無法在輸入時自動清除 (需手動刪除)。

漸進式增強:原生 JS 相容方案 (IE9+)

<input type="text" 
       id="legacyInput" 
       value="請輸入關鍵字..." 
       class="placeholder-fallback" 
       data-placeholder="請輸入關鍵字..." />

<style>
  .placeholder-fallback { color: #999; font-style: italic; }
  .placeholder-fallback.active { color: #333; font-style: normal; }
</style>

<script>
(function() {
  var input = document.getElementById('legacyInput');
  var placeholderText = input.getAttribute('data-placeholder') || input.value;
  
  // 初始化狀態
  function init() {
    if (!input.value || input.value === placeholderText) {
      input.value = placeholderText;
      input.classList.remove('active');
    } else {
      input.classList.add('active');
    }
  }
  
  input.addEventListener('focus', function() {
    if (this.value === placeholderText) {
      this.value = '';
      this.classList.add('active');
    }
  });
  
  input.addEventListener('blur', function() {
    if (!this.value.trim()) {
      this.value = placeholderText;
      this.classList.remove('active');
    }
  });
  
  // 表單提交前清理 (避免提交 placeholder 文字)
  input.form && input.form.addEventListener('submit', function() {
    if (input.value === placeholderText) input.value = '';
  });
  
  init();
})();
</script>

jQuery 版本 (舊專案維護用)

<input type="text" id="jqInput" value="請輸入..." class="placeholder-text" />

<style>
  .placeholder-text { color: #999; font-style: italic; }
  .placeholder-text.focused { color: #333; font-style: normal; }
</style>

<script>
$(function() {
  var $input = $('#jqInput');
  var placeholder = $input.val();
  
  $input.on('focus', function() {
    if ($(this).val() === placeholder) {
      $(this).val('').addClass('focused');
    }
  }).on('blur', function() {
    if (!$(this).val().trim()) {
      $(this).val(placeholder).removeClass('focused');
    }
  });
  
  // 表單提交清理
  $input.closest('form').on('submit', function() {
    if ($input.val() === placeholder) $input.val('');
  });
  
  // 現代瀏覽器偵測:若支援 placeholder,移除 JS 行為
  if ('placeholder' in document.createElement('input')) {
    $input.attr('placeholder', placeholder).val('').off('focus blur');
    $input.closest('form').off('submit.placeholder');
  }
});

進階:多行文字區域

<textarea id="msgBox" rows="4" placeholder="請輸入留言內容..."></textarea>

<style>
  #msgBox { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 4px; resize: vertical; }
  #msgBox::placeholder { color: #aaa; line-height: 1.5; }
</style>

// JS 版 (舊瀏覽器)
var textarea = document.getElementById('msgBox');
var placeholder = '請輸入留言內容...';
textarea.value = placeholder;
textarea.style.color = '#999';

textarea.addEventListener('focus', function() {
  if (this.value === placeholder) { this.value = ''; this.style.color = '#333'; }
});
textarea.addEventListener('blur', function() {
  if (!this.value.trim()) { this.value = placeholder; this.style.color = '#999'; }
});

常見陷阱與解決方案

問題 原因 解決方案
表單提交送出 placeholder 文字 未在 submit 前清空 form.onsubmit 中檢查並清空
密碼欄位顯示明文 placeholder type="password" 時 value 可見 使用原生 placeholder 或焦點時切換 type
自動填入 (Autofill) 觸發誤判 瀏覽器自動填入不觸發 focus 事件 使用 input 事件或 animationstart 偵測 autofill
IE11 placeholder 顏色無法修改 不支援 ::placeholder 偽元素 使用 :-ms-input-placeholder CSS hack

Autofill 偵測補強 (現代瀏覽器)

// 偵測瀏覽器自動填入
input.addEventListener('animationstart', function(e) {
  if (e.animationName === 'onAutoFillStart') {
    input.classList.add('active'); // 模擬聚焦狀態
  }
}, false);

// CSS 配合
@keyframes onAutoFillStart { from { opacity: 1; } to { opacity: 1; } }
input:-webkit-autofill { animation-name: onAutoFillStart; }

最佳實踐總結

  1. 新專案:直接使用 placeholder 屬性 + CSS ::placeholder 樣式化
  2. 需支援 IE9-10:使用 placeholder 屬性 + jQuery Placeholder Polyfill
  3. 舊專案維護:保留 JS 方案,但加上特性偵測自動降級
  4. 密碼欄位:永遠使用原生 placeholder,勿用 value 模擬
  5. 表單驗證:提交前務必過濾 placeholder 文字,避免汙染資料

隨著 IE 退役,原生 placeholder 已成主流標準。新專案應優先使用語意化 HTML,僅在極少數舊環境需求下採用 JavaScript 相容方案。

copyright © 萬盛學電腦網 all rights reserved