密碼框有個先天限制:<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>
password1(一個普通 text 框,內容是灰字「password」)。password1 藏起來、把真正的 password2 顯示出來並聚焦,使用者開始輸入的內容就會被圓點遮蔽。password2 收回、提示文字重新出現,畫面回到初始樣子。這個技巧在 HTML5 普及後已經有多個更乾淨的替代方案,建議優先採用:
<input type="password" placeholder="請輸入密碼"> 一行解決,瀏覽器原生處理、支援度良好,也不必額外 JS。缺點是聚焦時提示會消失、樣式客製性有限。:focus 與 :placeholder-shown 讓它滑到上方變小,兼顧提示與視覺彈性,是目前主流設計。type 屬性:$el.attr('type', $el.attr('type') === 'password' ? 'text' : 'password')。這才是使用者真正想要的功能。另外提醒:無論用哪種做法,提示文字都只是裝飾。後端驗證與前端非空檢查都不可省略,也不要因為「畫面上有提示」就以為使用者一定看得到——螢幕閱讀器需要靠 label 或 aria-label 才能正確朗讀欄位用途。