placeholder的兼容处理(jQuery下)

本文介绍了一种兼容老浏览器的placeholder属性实现方法,通过JavaScript检测浏览器是否支持placeholder,并为不支持该属性的浏览器提供回退方案。对于不支持的浏览器,通过模拟placeholder行为来显示提示信息。
/*
.placeholder{
color: #aaa!important;
}
span.placeholder{
position: absolute;
left: 0;
line-height: 34px;
padding-left: 12px;
}
*/
var browserSupport = {
placeholder: 'placeholder' in document.createElement('input')
}

/* ajax请求发现未登录时,服务端返回401错误,然后此处统一处理401错误,跳转到登录页面 */
$(document).ready(function() {
//模拟placeholder
if( !browserSupport.placeholder){
$('input[placeholder],textarea[placeholder]').each(function(){
var that = $(this),
text= that.attr('placeholder'),
oldType;
if(that.val()===""){
if(that.attr('type') != 'password'){
that.val(text).addClass('placeholder');
}else{
that.before('<span class="placeholder">请输入密码</span>');
}
}
that.focus(function(){
//ie8下readonly依然可以上焦点的处理
if(that.attr('readonly')){
that.blur();
return;
}
//清除span.placeholder
that.prev("span.placeholder").remove();
that.removeClass('placeholder');

if(that.val()===text){
that.val("");
}
}).blur(function(){
if(that.val()===""){
if(that.attr('type') != 'password'){
that.val(text).addClass('placeholder');
}else{
that.before('<span class="placeholder">请输入密码</span>');
}
//防止异常情况:当有placeholder类,且值不为空(代码设置值时容易出现)
}else{
that.removeClass('placeholder');
}
}).closest('form').submit(function(){
if(that.val() === text){
that.val('');
}
});
});
$(document).on('click','span.placeholder',function(){
$(this).next("[placeholder]").focus();
//删除span.placeholder会在[placeholder]的focus中进行
})
}
})


参考:http://www.cnblogs.com/chuaWeb/p/5062671.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值