placeholder的兼容处理(jQuery下)

82500798 2016-10-18

/*
.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

相关推荐