兼容IE8以下瀏覽器input表單屬性placeholder不能智能提示功能


當前很多表單提示使用了表單屬性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以下表單智能提示和表單驗證問題了~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM