萬盛學電腦網

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

jQuery 實現輸入框預設值提示(Placeholder 效果)兼容舊瀏覽器

需求背景

HTML5 placeholder 屬性在 IE9 以下不支援。使用 jQuery 模擬:聚焦時清空預設值,失焦為空則恢復預設值。

核心實現

$(function() {
    $(".input-hint").each(function() {
        var $this = $(this);
        var defaultVal = $this.val(); // 獲取初始值

        $this.focus(function() {
            if ($this.val() === defaultVal) {
                $this.val("").removeClass("hint-active");
            }
        }).blur(function() {
            if ($this.val() === "") {
                $this.val(defaultVal).addClass("hint-active");
            }
        });

        // 表單提交前清理提示值,避免提交到後端
        $this.closest("form").submit(function() {
            if ($this.val() === defaultVal) $this.val("");
        });
    });
});

CSS 樣式區分

.input-hint { color: #999; }        /* 提示態顏色 */
.input-hint.hint-active { color: #999; } /* 同樣樣式,或不加區分 */
.input-hint:focus { color: #333; }   /* 聚焦時正常顏色 */

HTML 使用示例

<input type="text" class="input-hint" value="請輸入用戶名" />
<input type="password" class="input-hint" value="請輸入密碼" />
<textarea class="input-hint">請輸入留言內容</textarea>

現代化替代方案

  • 原生 Placeholder + Polyfill:推薦使用 jquery-placeholder 或 Placeholders.js,自動檢測瀏覽器支持情況並填補。
  • CSS :placeholder-shown:現代瀏覽器可純 CSS 樣式化佔位符顏色:input::placeholder { color: #999; }。

注意事項

  1. 預設值不應包含敏感信息。
  2. 表單提交時務必清空提示值,否則後端會收到「請輸入用戶名」作為真實數據。
  3. 密碼框 type="password" 在舊 IE 中無法顯示明文提示,需切換 type="text" 再切回,或使用浮動 Label 方案。
copyright © 萬盛學電腦網 all rights reserved