input输入框placeholder属性兼容IE浏览器
因为placeholder属性是html5的新属性,在浏览器兼容方面只兼容新版浏览器,而相对应版本较低的IE浏览器并不支持,以下是解决方案:
var JPlaceHolder = {
//检测
_check : function(){
return 'placeholder' in document.createElement('input');
},
//初始化
init : function(){
if(!this._check()){
this.fix();
}
},
//修复
fix : function(){
jQuery(':input[placeholder]').each(function(index, element) {
var self = $(this), txt = self.attr('placeholder');
self.wrap($('').css({position:'relative', zoom:'1', border:'none', background:'none', padding:'none', margin:'none'}));
var pos = self.position(), h = self.outerHeight(true), paddingleft = self.css('padding-left');
var holder = $('').text(txt).css({position:'absolute', left:pos.left, top:(pos.top+7), height:h, lienHeight:h, paddingLeft:paddingleft, color:'#aaa',fontFamily:'微软雅黑'}).appendTo(self.parent());
self.focusin(
function(e) {
holder.hide();
}).focusout(function(e) {
if(!self.val()){
holder.show();
}
}); holder.click(function(e) {
holder.hide(); self.focus();
});
});
}
};
//执行
jQuery(function(){
JPlaceHolder.init();
});
第二种方法:
$(function () {
//兼容不支持placeholder的浏览器[ie浏览器,并且10以下均采用替代方式处理]
if ((navigator.appName == "Microsoft Internet Explorer") && (document.documentMode < 10 || document.documentMode == undefined)) {
var $placeholder = $("input[placeholder]");
for (var i = 0; i < $placeholder.length; i++) {
if ($placeholder.eq(i).attr("type") == "password") {
$placeholder.eq(i).siblings("label").text($placeholder.eq(i).attr("placeholder")).show()
} else {
$placeholder.eq(i).val($placeholder.eq(i).attr("placeholder")).css({"color": "#ccc"})
}
}
$placeholder.focus(function () {
if ($(this).attr("type") == "password") {
$(this).siblings("label").hide()
} else {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("").css({"color": "#333"})
}
}
}).blur(function () {
if ($(this).attr("type") == "password") {
if ($(this).val() == "") {
$(this).siblings("label").text($(this).attr("placeholder")).show()
}
} else {
if ($(this).val() == "") {
$(this).val($(this).attr("placeholder")).css({"color": "#ccc"})
}
}
});
}
});