萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

HTML5 placeholder 兼容性解決方案:原生支援與 Polyfill 實現

解決 IE9- 不支持 placeholder 的完整方案

HTML5 placeholder 屬性提供輸入框提示文字,現代瀏覽器完美支持,但 IE9 及以下不支持。本文提供純 JS Polyfill 方案與密碼框特殊處理技巧。

原生 placeholder 效果回顧

<input type="text" placeholder="請輸入用戶名">
<textarea placeholder="請輸入留言內容..."></textarea>

現代瀏覽器:聚焦時提示消失,失焦空值時恢復,提示文字顏色可通過 ::placeholder 偽元素自定義。

通用 Polyfill 實現 (原生 JS,無依賴)

/**
 * Placeholder Polyfill for IE9-
 * 用法: new PlaceholderPolyfill().init('input[placeholder], textarea[placeholder]');
 */
class PlaceholderPolyfill {
    constructor() {
        this.nativeSupport = 'placeholder' in document.createElement('input');
        this.activeElements = new WeakMap(); // 記錄原始值與狀態
    }

    init(selector) {
        if (this.nativeSupport) return; // 現代瀏覽器直接返回

        const elements = document.querySelectorAll(selector);
        elements.forEach(el => this.bind(el));
        
        // 動態添加的元素支持 (MutationObserver)
        if (window.MutationObserver) {
            new MutationObserver(mutations => {
                mutations.forEach(m => m.addedNodes.forEach(node => {
                    if (node.nodeType === 1) {
                        if (node.matches(selector)) this.bind(node);
                        node.querySelectorAll(selector).forEach(el => this.bind(el));
                    }
                }));
            }).observe(document.body, { childList: true, subtree: true });
        }
    }

    bind(el) {
        if (el._placeholderBound) return;
        el._placeholderBound = true;

        const placeholder = el.getAttribute('placeholder');
        if (!placeholder) return;

        // 初始狀態
        if (!el.value) {
            el.value = placeholder;
            el.style.color = '#999';
            this.activeElements.set(el, { isPlaceholder: true });
        }

        // 聚焦:清空提示
        el.addEventListener('focus', () => {
            const state = this.activeElements.get(el);
            if (state?.isPlaceholder) {
                el.value = '';
                el.style.color = '';
                this.activeElements.set(el, { isPlaceholder: false });
            }
        });

        // 失焦:恢復提示
        el.addEventListener('blur', () => {
            if (!el.value) {
                el.value = placeholder;
                el.style.color = '#999';
                this.activeElements.set(el, { isPlaceholder: true });
            } else {
                el.style.color = '';
                this.activeElements.set(el, { isPlaceholder: false });
            }
        });

        // 表單提交前清理佔位符值
        const form = el.closest('form');
        if (form && !form._placeholderSubmitBound) {
            form._placeholderSubmitBound = true;
            form.addEventListener('submit', () => {
                this.activeElements.forEach((state, el) => {
                    if (state.isPlaceholder) el.value = '';
                });
            });
        }
    }

    // 表單驗證前調用,確保提示值不被當作真實數據提交
    clearAll(selector) {
        document.querySelectorAll(selector).forEach(el => {
            const state = this.activeElements.get(el);
            if (state?.isPlaceholder) el.value = '';
        });
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    new PlaceholderPolyfill().init('input[placeholder], textarea[placeholder]');
});

密碼框特殊處理:切換 type 技巧

密碼框 type="password" 顯示為圓點,無法直接顯示 placeholder 明文。解決方案:雙輸入框切換。

HTML 結構

<div class="pwd-wrapper" style="position: relative;">
    <input type="text" id="pwd-placeholder" value="請輸入密碼" 
           style="color: #999;" autocomplete="off">
    <input type="password" id="pwd-real" style="display: none;" autocomplete="current-password">
</div>

JS 交互邏輯

const pwdPlaceholder = document.getElementById('pwd-placeholder');
const pwdReal = document.getElementById('pwd-real');

pwdPlaceholder.addEventListener('focus', () => {
    pwdPlaceholder.style.display = 'none';
    pwdReal.style.display = 'block';
    pwdReal.focus();
});

pwdReal.addEventListener('blur', () => {
    if (!pwdReal.value.trim()) {
        pwdReal.style.display = 'none';
        pwdPlaceholder.style.display = 'block';
    }
});

// 表單提交時確保真實值被提交
document.querySelector('form')?.addEventListener('submit', () => {
    if (pwdPlaceholder.style.display !== 'none') {
        pwdPlaceholder.disabled = true; // 防止提交佔位符值
    }
});

現代瀏覽器原生樣式控制

/* 修改 placeholder 顏色 */
::placeholder { color: #999; opacity: 1; } /* Firefox 需 opacity:1 */
::-webkit-input-placeholder { color: #999; } /* WebKit/Blink */
:-ms-input-placeholder { color: #999; }      /* IE10-11 */
::-ms-input-placeholder { color: #999; }     /* Edge (舊版) */

/* 修改 placeholder 字體樣式 */
::placeholder { font-style: italic; font-size: 0.9em; }

最佳實踐建議

  1. 優雅降級:現代瀏覽器用原生,舊瀏覽器載入 Polyfill (可用 <!--[if lt IE 10]><script src="placeholder-polyfill.js"></script><![endif]-->)
  2. 無障礙:placeholder **不是** <label> 替代品,必須提供關聯的 <label> 或 aria-label
  3. 不要放關鍵信息:提示文字會在輸入時消失,重要格式要求(如「手機號格式:11 位數字」)應放在輸入框下方
  4. 密碼框:優先使用雙輸入框切換方案,或現代瀏覽器直接用原生 <input type="password" placeholder="...">
copyright © 萬盛學電腦網 all rights reserved