輸入框裡那層灰色的「請輸入帳號」,該怎麼實作?最偷懶的寫法是把提示文字塞進 value,但這會直接把提示內容當成使用者輸入送出後端,實務上絕對不行。以下是三種不把提示寫進 value 的做法。
把提示文字用 <span> 絕對定位蓋在輸入框上,點擊或聚焦時讓它消失。
<label class="password">
<span class="passText" onClick="CHECKON.hide(this, oldpwd)" id="oldPass">原密碼</span>
<input type="password" name="oldpwd" id="oldpwd"
onfocus="CHECKON.showHelpInfo(this);"
class="text" autocomplete="off" />
</label>
.password { position:relative; }
.passText {
position:absolute; left:5px; top:0px;
color:#a9a9a9; font-size:14px;
}
var CHECKON = {
showHelpInfo: function (idTa) {
// previousSibling 可能抓到文字節點,要判斷 nodeType 往上一層找
var pve = (idTa.previousSibling.nodeType == 1)
? idTa.previousSibling
: idTa.previousSibling.previousSibling;
pve.style.display = 'none';
},
hide: function (classN, id2) {
var idBox = document.getElementById(id2);
classN.style.display = 'none';
idBox.focus();
}
};
這裡有個真的會踩到的細節:previousSibling 找的是「兄弟節點」,包含空白與換行產生的文字節點,不保證拿到的是元素。所以必須判斷 nodeType == 1,必要時再往前一層。與其這樣繞,不如直接用 previousElementSibling,它只找元素節點:
var pve = idTa.previousElementSibling;
把提示文字做成背景圖貼在 input 上,聚焦時把背景拿掉。優點是完全不佔 DOM;缺點是文字不能更換、不能翻譯,而且 IE7 下有相容問題。
input { background:url(img/hint.png) no-repeat 5px center; }
input:focus { background-image:none; }
<input type="text" placeholder="請輸入帳號" />
瀏覽器自動以灰色呈現,輸入時自動消失,而且永遠不會被當成值送出。缺點是舊版 IE(IE9 以下)不支援——但在今天,這已經不是需要妥協的理由了。
瀏覽器會快取上次輸入的帳號密碼,再次打開登入頁時自動帶出。對於做法一(span 疊字)來說,這會造成「提示文字」和「自動填入的值」重疊;做法二用背景圖大致能避開,但 IE7 仍會出問題。
要關掉表單快取,可以在 <head> 加上:
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
或直接在表單上關閉自動完成:
<form autocomplete="off">
不過要提醒兩點:這些 meta 標籤對快取的抑制效果在各瀏覽器並不一致;而現代主流瀏覽器基於使用者利益,會無視 autocomplete="off",尤其是帳號密碼欄位。所以與其想辦法阻止,不如把設計做對——用 placeholder,重影問題從根上就不存在。