placeholder 是 HTML5 新增的屬性。在 input 上設定它之後,該文字會以灰色提示的形式顯示在輸入框內,一旦取得焦點就自動消失。這個效果在現代瀏覽器上是原生支援的,但舊版 IE 完全不認,於是就有了這個外掛。
外掛並不嘗試「讓 IE 認得 placeholder 屬性」,而是走一段更實際的路:先偵測瀏覽器是否原生支援,不支援時才介入,用 jQuery 模擬出相同的外觀與行為。
其中密碼框是最麻煩的部分。因為基於安全考量,DOM 不允許直接修改 input 的 type,所以必須複製一份屬性、重建一個 type="text" 的新節點來充當提示層,取得焦點時再把真正的密碼框顯示出來。
(function ($) {
var placeholderfriend = {
focus: function (s) {
s = $(s).hide().prev().show().focus();
// 還原被暫時加上標記的 id 與 class
var idValue = s.attr("id");
if (idValue) s.attr("id", idValue.replace("placeholderfriend", ""));
var clsValue = s.attr("class");
if (clsValue) s.attr("class", clsValue.replace("placeholderfriend", ""));
}
};
// 先判斷是否原生支援
function isPlaceholer() {
var input = document.createElement('input');
return "placeholder" in input;
}
if (!isPlaceholer()) {
$(function () {
// 文字框:直接操作 value
var elements = $('input[type="text"][placeholder]');
elements.each(function () {
var s = $(this), pValue = s.attr("placeholder");
if (pValue && s.val() == '') s.val(pValue);
});
elements.focus(function () {
var s = $(this), pValue = s.attr("placeholder");
if (s.val() == pValue) s.val('');
});
elements.blur(function () {
var s = $(this), pValue = s.attr("placeholder");
if (!s.val()) s.val(pValue);
});
// 密碼框:無法改 type,必須重建節點
var elementsPass = $('input[type="password"][placeholder]');
elementsPass.each(function (i) {
var s = $(this), pValue = s.attr("placeholder");
if (!pValue || s.val() != '') return;
var html = this.outerHTML || "";
html = html.replace(/\s*type=(['"])?password\1/gi, " type=text placeholderfriend")
.replace(/\s*(value|on[a-z]+|name)(=(['"])?\S*\3)?/gi, " ")
.replace(/\s*placeholderfriend/,
" placeholderfriend value='" + pValue + "' " +
"onfocus='placeholderfriendfocus(this);'");
// 暫時替 id / class 加上標記,避免與提示層混淆
var idValue = s.attr("id");
if (idValue) s.attr("id", idValue + "placeholderfriend");
var clsValue = s.attr("class");
if (clsValue) s.attr("class", clsValue + "placeholderfriend");
s.hide();
s.after(html);
});
elementsPass.blur(function () {
var s = $(this);
if (s.val() == '') s.hide().next().show();
});
});
}
window.placeholderfriendfocus = placeholderfriend.focus;
})(jQuery);
只要依序載入 jQuery、外掛,然後照常寫 HTML5 的 placeholder 即可,不需要額外設定。
<html> <head> <script src="jquery.js" type="text/javascript"></script> <script src="placeholderfriend.js" type="text/javascript"></script> </head> <body> <input placeholder="賬號/手機號碼"><br> <input placeholder="密碼" type="password"> </body> </html>
特性偵測而非瀏覽器判斷。用 "placeholder" in input 來確認支援與否,比解析 user agent 猜測版本可靠得多,也是現代前端該有的習慣。
漸進增強。支援的瀏覽器完全不執行任何額外程式碼,只有不支援的環境才付出模擬的成本。
用 id/class 標記來配對兩個節點。密碼框被拆成「提示層」與「真實層」之後,需要一個方式在 focus 時找回彼此,加上後綴標記再於切換時移除,是個直覺又不衝突的做法。
不過也得誠實說:在今日專案中,IE8 以下的支援需求已大幅降低,這個外掛的實用價值主要轉為「閱讀他人如何優雅地做漸進增強」。若只是想補 placeholder,用 ::placeholder 加上現成的 polyfill 會輕鬆許多。