萬盛學電腦網

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

Input 輸入框提示文字顯示/隱藏交互實現指南(Placeholder 現代方案與兼容降級)

輸入框提示文字(Placeholder)隨焦點顯示隱藏是經典交互需求。現代瀏覽器原生支持 `placeholder` 屬性,但舊項目仍需 JS 實現。本文對比原生與 JS 方案,提供完整兼容性處理。

現代標準:原生 placeholder 屬性(零 JS)


<input type="text" placeholder="請輸入您的姓名">
<input type="search" placeholder="搜索商品...">
<textarea placeholder="請輸入反饋內容"></textarea>

優勢:無需 JS、性能最佳、無障礙友好、移動端原生體驗、CSS 可樣式化(`::placeholder`)。

CSS 樣式化


/* 修改提示文字顏色 */
::placeholder { color: #999; opacity: 1; } /* Firefox 19+ */
:-ms-input-placeholder { color: #999; }     /* IE 10-11 */
::-ms-input-placeholder { color: #999; }    /* Edge */

/* 輸入框聚焦時淡化提示 */
:focus::placeholder { opacity: 0.5; transition: opacity 0.3s; }

舊瀏覽器/特殊需求:JS 實現方案

核心邏輯


// 原理:focus 時若值等於提示文字則清空;blur 時若為空則恢復提示文字
function setupPlaceholder(inputId, placeholderText) {
    var input = document.getElementById(inputId);
    if (!input) return;

    // 初始化
    if (!input.value) {
        input.value = placeholderText;
        input.classList.add("placeholder-active");
    }

    // 聚焦:清空提示
    input.onfocus = function() {
        if (this.value === placeholderText) {
            this.value = "";
            this.classList.remove("placeholder-active");
        }
    };

    // 失焦:恢復提示
    input.onblur = function() {
        if (this.value === "") {
            this.value = placeholderText;
            this.classList.add("placeholder-active");
        }
    };

    // 表單提交前清理(防止提交提示文字)
    var form = input.form;
    if (form) {
        form.onsubmit = function() {
            if (input.value === placeholderText) {
                input.value = "";
            }
        };
    }
}

// 使用
setupPlaceholder("username", "請輸入您的姓名");
setupPlaceholder("search", "搜索商品...");

jQuery 版本(兼容舊項目)


$.fn.placeholder = function(text) {
    return this.each(function() {
        var $this = $(this);
        var placeholder = text || $this.attr("data-placeholder") || "請輸入內容";

        // 初始化
        if (!$this.val()) {
            $this.val(placeholder).addClass("placeholder");
        }

        $this.on("focus", function() {
            if ($this.val() === placeholder) {
                $this.val("").removeClass("placeholder");
            }
        }).on("blur", function() {
            if (!$this.val()) {
                $this.val(placeholder).addClass("placeholder");
            }
        });

        // 表單提交清理
        $this.closest("form").on("submit", function() {
            if ($this.val() === placeholder) $this.val("");
        });
    });
};

// 使用
$("#username").placeholder("請輸入您的姓名");
$("#search").placeholder("搜索...");

關鍵細節與避坑

1. 表單提交時提示文字被提交

必須在 `form.onsubmit` 中清空等於提示文字的值,或服務端過濾。

2. 密碼框類型切換技巧


// 密碼框無法直接設置 placeholder 顯示明文(安全限制)
// 方案:焦點時動態切換 type



						
copyright © 萬盛學電腦網 all rights reserved