萬盛學電腦網

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

jQuery 表單輸入框焦點/輸入時提示文字顯示隱藏效果

前言

表單輸入框常見的 UX 模式:預設顯示灰色提示文字(Placeholder 文字),使用者聚焦或開始輸入時隱藏,失焦且無輸入內容時恢復顯示。本文提供兩種模式的完整實作:聚焦隱藏與輸入隱藏,並附上 CSS 樣式。

完整 HTML + JS + CSS

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>表單提示文字效果</title>
<style>
form { width:400px; margin:10px auto; border:1px solid #E0DEDE; background:#FCF9EF; padding:30px; box-shadow:0 1px 10px rgba(0,0,0,0.1) inset; }
label { display:block; height:40px; position:relative; margin:20px 0; }
span { position:absolute; left:10px; line-height:40px; color:#BCBCBC; cursor:text; }
.input_txt { width:398px; border:1px solid #ccc; box-shadow:0 1px 10px rgba(0,0,0,0.1) inset; height:38px; text-indent:10px; }
.input_txt:focus { box-shadow:0 0 4px rgba(255,153,164,0.8); border:1px solid #B00000; }
h2 { font-family:"Microsoft JhengHei"; text-shadow:1px 1px 3px #fff; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
    // 模式一:聚焦隱藏
    $("#focus .input_txt").each(function() {
        var $input = $(this), $tip = $input.siblings("span");
        $input.val() ? $tip.hide() : $tip.show();

        $input.focus(function() { $tip.hide(); })
            .blur(function() { $input.val() ? $tip.hide() : $tip.show(); });
    });

    // 模式二:輸入時隱藏(keyup)
    $("#keydown .input_txt").each(function() {
        var $input = $(this), $tip = $input.siblings("span");
        $input.val() ? $tip.hide() : $tip.show();

        $input.keyup(function() { $tip.hide(); })
            .blur(function() { $input.val() ? $tip.hide() : $tip.show(); });
    });
});
</script>
</head>
<body>
<form id="focus" class="border_radius">
    <h2>聚焦型提示語消失</h2>
    <label><span>電子郵件</span><input type="text" class="input_txt border_radius" /></label>
    <label><span>密碼</span><input type="password" class="input_txt border_radius" /></label>
</form>

<form id="keydown" class="border_radius">
    <h2>輸入型提示語消失</h2>
    <label><span>電子郵件</span><input type="text" class="input_txt border_radius" /></label>
    <label><span>密碼</span><input type="password" class="input_txt border_radius" /></label>
</form>
</body>
</html>

現代替代方案:HTML5 Placeholder

<input type="text" placeholder="電子郵件" class="input_txt">
<input type="password" placeholder="密碼" class="input_txt">
  • 原生 placeholder 免寫 JS,瀏覽器原生支援、無障礙友善。
  • 若需支援 IE9 以下,可搭配 jQuery Placeholder Polyfill。

進階優化

  • 使用 ::placeholder 偽元素自訂提示文字樣式(顏色、字體)。
  • 結合 required、pattern 進行原生驗證。
  • 若提示文字包含 HTML 或需複雜邏輯,才建議用 JS 方案。
copyright © 萬盛學電腦網 all rights reserved