DIV CSS 佈局教程網

密碼框顯示提示文字的 jQuery 做法:focus/blur 雙層切換
編輯:JQuery特效代碼     

密碼框有個先天限制:<input type="password"> 的內容一律顯示為圓點,沒辦法像一般文字框那樣放一行「請輸入密碼」的灰字提示。常見的解法是用兩個輸入框疊在一起:一個顯示提示的 text 框,一個真正的 password 框,依焦點狀態切換顯示。

完整範例

<html>
<head>
<title>登錄</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script>
$(document).ready(function () {
    $(".text_login").focus(function () {
        if ($(this).val() == 'user name' || $(this).val() == 'password') {
            $(this).val('');                       // 聚焦時清掉提示文字
        }
        if ($(this).attr('id') == 'password1') {
            $(this).hide();                        // 隱藏提示用的 text 框
            $('#password2').show();                // 顯示真正的密碼框
            $('#password2').focus();
        }
    });

    $(".text_login").blur(function () {
        if ($(this).attr('id') == 'password2' && $(this).val() == '') {
            $(this).hide();                        // 密碼框沒填 → 退回提示狀態
            $('#password1').show();
            $('#password1').val('password');
        }
        else if ($(this).attr('id') == 'uname' && $(this).val() == '') {
            $(this).val('user name');              // 帳號欄沒填 → 補回提示
        }
    });
});
</script>
</head>

<body>
<table cellpadding="0" cellspacing="0" class="tb_login" border="0">
<tr>
    <td>賬號:</td>
    <td><input type="text" name="uname" value="user name"
               id="uname" class="text_login" /></td>
</tr>
<tr>
    <td>密碼:</td>
    <td>
        <input type="text" value="password" id="password1" class="text_login" />
        <input type="password" id="password2" style="display:none;"
               class="text_login" />
    </td>
</tr>
</table>
</body>
</html>

運作邏輯

  1. 初始狀態:帳號欄顯示「user name」,密碼位置顯示的是 password1(一個普通 text 框,內容是灰字「password」)。
  2. 聚焦密碼欄時:立刻把 password1 藏起來、把真正的 password2 顯示出來並聚焦,使用者開始輸入的內容就會被圓點遮蔽。
  3. 離開且密碼為空時:把 password2 收回、提示文字重新出現,畫面回到初始樣子。

今天更好的做法

這個技巧在 HTML5 普及後已經有多個更乾淨的替代方案,建議優先採用:

  • placeholder 屬性。 <input type="password" placeholder="請輸入密碼"> 一行解決,瀏覽器原生處理、支援度良好,也不必額外 JS。缺點是聚焦時提示會消失、樣式客製性有限。
  • 浮動標籤(floating label)。 用 label 疊在輸入框上,搭配 :focus 與 :placeholder-shown 讓它滑到上方變小,兼顧提示與視覺彈性,是目前主流設計。
  • 真的需要「顯示密碼」功能時,與其切換兩個輸入框,不如加一個眼睛圖示按鈕切換 type 屬性:$el.attr('type', $el.attr('type') === 'password' ? 'text' : 'password')。這才是使用者真正想要的功能。

另外提醒:無論用哪種做法,提示文字都只是裝飾。後端驗證與前端非空檢查都不可省略,也不要因為「畫面上有提示」就以為使用者一定看得到——螢幕閱讀器需要靠 label 或 aria-label 才能正確朗讀欄位用途。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved