標籤:
由於placeholder是html5的新屬性,在IE8、IE9下是不能顯示的,有相容性問題。
解決思路:
1.判斷目前瀏覽器是否支援placeholder屬性
2.若不支援,則將type="text"的input標籤的value值設定為placeholder的值,類比placeholder效果;若是type="password",則添加一個type="password"的input元素類比。
代碼:
<div> <input id="account" style="height: 45px; padding: 6px 25px; line-height: 31px" type="text" class="form-control" placeholder="使用者名稱/手機號" ></div><div id="pwdDiv"> <input id="password" style="height: 45px; padding:6px 25px; line-height: 31px" type="password" class="form-control" placeholder="密碼"></div>
(function($){ //判斷瀏覽器是否支援placeholder屬性 var supportPlaceholder = ‘placeholder‘in document.createElement(‘input‘); //初始化 var placeholder = function(input){ var text = input.attr(‘placeholder‘); var defaultValue = input.defaultValue; if(!defaultValue && input.attr(‘type‘) == "text"){ input.val(text); } }; //當瀏覽器不支援placeholder屬性時,調用placeholder函數 if(!supportPlaceholder){ $(‘<input id="showpwd" style="height: 45px; padding:6px 25px;line-height: 31px" type="text" class="form-control" placeholder="密碼">‘).appendTo(‘#pwdDiv‘); $(‘#password‘).hide(); $(‘input‘).each(function(){ placeholder($(this)) }); $("input").focus(function () { var placeTexr=$(this).attr("placeholder"); var value = $(this).attr("value"); // alert(placeTexr); if($(this).attr("id") == "showpwd"){ $(this).hide(); $(‘#password‘).show().focus(); }else if($(this).attr("type") == "text" && $(this).val() ==placeTexr ){ $(this).val(""); } }); $("input").focusout(function () { var placeTexr=$(this).attr("placeholder"); var test=$(this).val(); if($(this).attr("id") == "password" && $(this).val() == ""){ $(this).hide(); $(‘#showpwd‘).show(); } if($(this).attr("type") == "text" && $(this).val() =="" ){ $(this).val(placeTexr); } }); } })($);
js解決IE8、9下placeholder的相容問題