placeholder屬性是HTML5新添加的屬性,當(dāng)input或者textarea設(shè)置了該屬性后蔽午,該值的內(nèi)容將作為灰色提示顯示在文本框中樟遣,當(dāng)文本框獲得焦點(diǎn)時(shí),提示文字消失姿骏,placeholder可作為輸入框的提示文字
效果圖
Paste_Image.png
placeholder是常用的屬性糖声,它使得input框內(nèi)有很友好的提示效果。高版本瀏覽器都支持placeholder屬性分瘦,但I(xiàn)E9以下版本的瀏覽器并不支持這一屬性蘸泻。這里用JavaScript實(shí)現(xiàn)添加對(duì)瀏覽器的兼容處理。
function isPlaceholder(){
var input = document.createElement('input');
return 'placeholder' in input;
}
if (!isPlaceholder()) {//不支持placeholder 用jquery來完成
$(document).ready(function() {
if(!isPlaceholder()){
$("input").not("input[type='password']").each(//把input綁定事件 排除password框
function(){
if($(this).val()=="" && $(this).attr("placeholder")!=""){
$(this).val($(this).attr("placeholder"));
$(this).focus(function(){
if($(this).val()==$(this).attr("placeholder")) $(this).val("");
});
$(this).blur(function(){
if($(this).val()=="") $(this).val($(this).attr("placeholder"));
});
}
});
//對(duì)password框的特殊處理1.創(chuàng)建一個(gè)text框 2獲取焦點(diǎn)和失去焦點(diǎn)的時(shí)候切換
$("input[type='password']").each(
function() {
var pwdField = $(this);
var pwdVal = pwdField.attr('placeholder');
pwdField.after('<input class="login-input" type="text" value='+pwdVal+' autocomplete="off" />');
var pwdPlaceholder = $(this).siblings('.login-input');
pwdPlaceholder.show();
pwdField.hide();
pwdPlaceholder.focus(function(){
pwdPlaceholder.hide();
pwdField.show();
pwdField.focus();
});
pwdField.blur(function(){
if(pwdField.val() == '') {
pwdPlaceholder.show();
pwdField.hide();
}
});
})
}
});
}
導(dǎo)入這個(gè)js就可以兼容ie9以下不顯示placeholder的問題了