IE下支援文字框和密碼框placeholder效果的JQuery外掛分享
阿新 • • 發佈:2018-11-10
placeholder是HTML5新增的一個屬性,當input設定了該屬性後,該值的內容將作為灰色提示顯示在文字框中,當文字框獲得焦點時,提示文字消失。
實現程式碼如下:
(function($) { var placeholderfriend = { focus: function(s) { s = $(s).hide().prev().show().focus(); 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", "")); } } } //判斷是否支援placeholder function isPlaceholer() { var input = document.createElement('input'); return "placeholder" in input; } //不支援的程式碼 if (!isPlaceholer()) { $(function() { var form = $(this); //遍歷所有文字框,新增placeholder模擬事件 var elements = form.find("input[type='text'][placeholder]"); elements.each(function() { var s = $(this); var pValue = s.attr("placeholder"); var sValue = s.val(); if (pValue) { if (sValue == '') { s.val(pValue); } } }); elements.focus(function() { var s = $(this); var pValue = s.attr("placeholder"); var sValue = s.val(); if (sValue && pValue) { if (sValue == pValue) { s.val(''); } } }); elements.blur(function() { var s = $(this); var pValue = s.attr("placeholder"); var sValue = s.val(); if (!sValue) { s.val(pValue); } }); //遍歷所有密碼框,新增placeholder模擬事件 var elementsPass = form.find("input[type='password'][placeholder]"); elementsPass.each(function(i) { var s = $(this); var pValue = s.attr("placeholder"); var sValue = s.val(); if (pValue) { if (sValue == '') { //DOM不支援type的修改,需要複製密碼框屬性,生成新的DOM var html = this.outerHTML || ""; html = html.replace(/\s*type=(['"])?password\1/gi, " type=text placeholderfriend") .replace(/\s*(?:value|on[a-z]+|name)(=(['"])?\S*\1)?/gi, " ") .replace(/\s*placeholderfriend/, " placeholderfriend value='" + pValue + "' " + "onfocus='placeholderfriendfocus(this);' "); 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); var sValue = s.val(); if (sValue == '') { 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().next().show(); } }); }); } window.placeholderfriendfocus = placeholderfriend.focus; })(jQuery);
使用很簡單,例子如下:
<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>