兼容IE8以下浏览器input表单属性placeholder不能智能提示功能

时间:2022-05-22 08:49:14

当前很多表单提示使用了表单属性placeholder,可这属性不兼容IE8以下的浏览器,我自己写了一个兼容处理js

// 兼容IE8以下浏览器input不能智能提示功能
if(navigator.appName == "Microsoft Internet Explorer" && (navigator.appVersion.match(/7./i)=="7." || navigator.appVersion.match(/8./i)=="8." || navigator.appVersion.match(/6./i)=="6." || navigator.appVersion.match(/5./i)=="5.")){
$('input[type=text]').each(function(index, val) {
var input = $(this);
if(input.attr('placeholder')!=''){
var def_val = input.attr('placeholder')
var def_color = input.css('color') // 默认表单原有颜色
var tip_color = '#999' // 提示信息的颜色
input.css('color',tip_color)
input.val(def_val)
input.on('focus', function(event) {
input.css('color',def_color)
if(input.val() == def_val){
input.val('')
}
});
input.on('blur', function(event) {
if(input.val() == '' || input.val() == def_val){
input.css('color',tip_color)
input.val(def_val)
}
});
}
});
}

以上代码可以达到兼容IE8以下的浏览器的智能提示的效果,但是验证表单却会出问题,特别是我用的jq表单验证插件validate。

原因在于,IE8以下默认给input表单value='提示信息',这样值本身不为空的情况下,用validate验证必填(required:true)时会失效。

我的处理方法是,在jquery.validate.js文件里required验证方法内添加验证其value值不能等于placeholder值,代码如下:

        // http://docs.jquery.com/Plugins/Validation/Methods/required
required: function( value, element, param ) {
// check if dependency is met
if ( !this.depend(param, element) ) {
return "dependency-mismatch";
}
if ( element.nodeName.toLowerCase() === "select" ) {
// could be an array for select-multiple or a string, both are fine this way
var val = $(element).val();
return val && val.length > 0;
}
if ( this.checkable(element) ) {
return this.getLength(value, element) > 0;
}
return ( $.trim(value).length > 0 ) && ( $.trim(value) != $(element).attr('placeholder') ); // 添加验证其value值不能等于placeholder值
}

这样就能圆满解决IE8以下表单智能提示和表单验证问题了~