萬盛學電腦網

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

實現 Placeholder 兼容方案總結:三種主流實現對比

背景

HTML5 `` 在舊版瀏覽器(IE9-)不支持。早期項目需用 JS 模擬。現代項目**原生 placeholder 已足夠**,本文作為歷史方案參考。

方案一:兄弟節點 Span 覆蓋(視覺最完美)

原理

在 `` 旁放置 `` 絕對定位覆蓋,輸入內容時隱藏,失焦為空時顯示。

HTML 結構

<div class="input-wrapper" style="position: relative;">
  <input class="ph-input" type="text" />
  <span class="ph-text" style="
    position: absolute; left: 10px; top: 50%; transform: translateY(-50%);
    color: #999; pointer-events: none; white-space: nowrap;
  ">請輸入手機號/郵箱</span>
</div>

JS 實現

function initPlaceholder($input, $text) {
    $input.on('input focus blur', function() {
        const val = $.trim($(this).val());
        $text.toggle(val === '');
    });
    
    $text.on('click', function() {
        $(this).prev('.ph-input').focus();
    });
    
    // 初始狀態
    $input.trigger('blur');
}

// 使用
$('.input-wrapper').each(function() {
    initPlaceholder($(this).find('.ph-input'), $(this).find('.ph-text'));
});

優缺點

優點缺點
視覺效果 100% 一致(含密碼框)需額外 DOM 節點,HTML 結構較重
支持所有 input 類型(含 password)動態表單需重新初始化
無焦點閃爍問題響應式佈局需配合 CSS 調整位置

方案二:value 值切換(輕量、無額外 DOM)

原理

利用自定義屬性 `data-placeholder` 存儲提示文本,焦點時清空,失焦為空時恢復。

HTML

<input class="ph-input" type="text" data-placeholder="請輸入用戶名" />
<input class="ph-input" type="password" data-placeholder="請輸入密碼" /> <!-- 無法顯示明文提示 -->

JS 實現

function initPlaceholderV2($inputs, tipColor = '#999', textColor = '#333') {
    $inputs.each(function() {
        const $this = $(this);
        const placeholder = $this.data('placeholder') || $this.attr('placeholder');
        
        // 初始化
        if (!$.trim($this.val())) {
            $this.val(placeholder).css('color', tipColor);
        } else {
            $this.css('color', textColor);
        }
    }).on('focus', function() {
        const $this = $(this);
        const placeholder = $this.data('placeholder') || $this.attr('placeholder');
        if ($this.val() === placeholder) {
            $this.val('').css('color', textColor);
        }
    }).on('blur', function() {
        const $this = $(this);
        const placeholder = $this.data('placeholder') || $this.attr('placeholder');
        if (!$.trim($this.val())) {
            $this.val(placeholder).css('color', tipColor);
        }
    }).closest('form').on('submit', function() {
        // 提交前清理佔位符,防止作為值提交
        $(this).find('.ph-input').each(function() {
            const $this = $(this);
            const placeholder = $this.data('placeholder') || $this.attr('placeholder');
            if ($this.val() === placeholder) $this.val('');
        });
    });
}

優缺點

優點缺點
無額外 DOM,輕量簡單不支持 password 類型(提示會顯示為黑點)
兼容性極好焦點時提示立即消失(原生 placeholder 需輸入才消失)
易於表單序列化(提交前清理)value 被佔用,獲取真實值需判斷

方案三:原生 placeholder + 降級填充(現代推薦)

原理

現代瀏覽器用原生,舊瀏覽器檢測不支持時啟用方案二。

實現

function initNativePlaceholderFallback() {
    // 檢測原生支持
    const nativeSupported = 'placeholder' in document.createElement('input');
    if (nativeSupported) return; // 現代瀏覽器直接用原生
    
    // 舊瀏覽器降級
    $('input[placeholder], textarea[placeholder]').each(function() {
        const $this = $(this);
        $this.data('placeholder', $this.attr('placeholder'))
             .removeAttr('placeholder'); // 移除原生屬性防干擾
    });
    initPlaceholderV2($('input[data-placeholder], textarea[data-placeholder]'));
}

// 頁面加載執行
$(initNativePlaceholderFallback);

優缺點

優點缺點
現代瀏覽器零成本、原生體驗不同瀏覽器表現不一致(原生 vs 模擬)
代碼維護簡單仍有 password 類型無法完美模擬問題

方案選擇建議

場景推薦方案理由
登錄/註冊頁(含密碼框)方案一視覺完美、支持 password、體驗一致
後台表單、搜索框(無密碼框)方案二/三輕量、易維護、無額外 DOM
現代項目(IE10+)**原生 placeholder**零代碼、標準、無障礙支持最好

現代最佳實踐(2024+)

<!-- 直接用原生,無需任何 JS -->
<input type="text" placeholder="請輸入關鍵詞" />
<input type="password" placeholder="請輸入密碼" />
<textarea placeholder="請輸入描述..."></textarea>

// CSS 美化(可選)
::placeholder { color: #999; opacity: 1; } /* Firefox 需 opacity:1 */
:focus::placeholder { color: transparent; } /* 聚焦隱藏 */

**結論**:2024 年新項目**直接使用原生 ``**,配合 CSS 美化即可。僅維護極舊項目(IE9-)時參考上述方案。

copyright © 萬盛學電腦網 all rights reserved