萬盛學電腦網

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

Input 輸入框焦點提示文字:原生 onfocus/onblur 實現與現代 placeholder 替代方案

原文方案(內聯事件屬性)

<input type="text" name="name" value="請輸入2-5個中文名字" 
  onfocus="if (this.value == '請輸入2-5個中文名字') this.value = ''"
  onblur="if (this.value == '') this.value = '請輸入2-5個中文名字'">

缺點:行為與結構耦合、值硬編碼在 HTML 中、無法區分用戶主動輸入同樣文字、密碼框無法顯示提示文本(需切換 type)。

現代標準方案:HTML5 placeholder 屬性

<input type="text" name="name" placeholder="請輸入2-5個中文名字">
<input type="tel" name="tel" placeholder="請輸入您的電話">
<input type="password" name="pwd" placeholder="請輸入密碼">

優勢:

  • 原生實現,無 JS 依賴,性能最佳
  • 密碼框自動顯示明文提示,聚焦時自動隱藏
  • 表單提交時不會發送 placeholder 值
  • CSS 可自定義樣式:::placeholder { color: #999; opacity: 1; }
  • 無障礙支援:屏幕閱讀器自動朗讀

兼容性處理(IE9- 不支援 placeholder)

// 簡易 Polyfill
if (!('placeholder' in document.createElement('input'))) {
  $('input[placeholder], textarea[placeholder]').each(function() {
    var $this = $(this);
    var placeholder = $this.attr('placeholder');
    
    function show() {
      if ($this.val() === '') {
        $this.val(placeholder).addClass('placeholder');
        if ($this.is('[type=password]')) {
          // 密碼框需創建鏡像文本框
          var $mirror = $this.clone().attr('type', 'text').val(placeholder).addClass('placeholder-mirror');
          $this.hide().after($mirror);
          $mirror.on('focus', function() {
            $mirror.hide();
            $this.show().focus();
          });
        }
      }
    }
    
    function hide() {
      if ($this.hasClass('placeholder')) {
        $this.val('').removeClass('placeholder');
      }
      $this.next('.placeholder-mirror').remove();
      $this.show();
    }
    
    $this.on('focus', hide).on('blur', show);
    show(); // 初始化
  });
}

進階:浮動標籤(Material Design 風格)

<div class="form-field">
  <input type="text" id="name" required>
  <label for="name">請輸入2-5個中文名字</label>
</div>

<style>
.form-field { position: relative; margin: 20px 0; }
.form-field input { width: 100%; padding: 10px 0; border: none; border-bottom: 1px solid #ccc; background: transparent; }
.form-field label { 
  position: absolute; left: 0; top: 10px; color: #999; 
  transition: all .2s; pointer-events: none; 
}
.form-field input:focus + label,
.form-field input:not(:placeholder-shown) + label { /* 需配合 placeholder */
  top: -18px; font-size: 12px; color: #3498db;
}
.form-field input:focus { border-bottom-color: #3498db; outline: none; }
</style>

Vue/React 組件化封裝示例

<!-- Vue 3 -->
<script setup>
defineProps(['label', 'type', 'placeholder']);
const props = defineProps({ modelValue: String, emit: ['update:modelValue'] });
const input = ref('');
watch(input, v => emit('update:modelValue', v));
</script>
<template>
  <div class="form-field">
    <input :type="type" :placeholder="placeholder" v-model="input" @focus="$emit('focus')" @blur="$emit('blur')">
    <label>{{ label }}</label>
  </div>
</template>

總結建議

  1. 優先使用原生 placeholder:零成本、最佳體驗、標準語義。
  2. 需兼容 IE9-:引入輕量 Polyfill(如上方代碼或 placeholders.js)。
  3. 追求視覺升級:浮動標籤模式,提升表單質感。
  4. 避免:內聯 onfocus/onblur 硬編碼值、手動切換 type=password/text(安全風險)、重複造輪子。
copyright © 萬盛學電腦網 all rights reserved