首頁 > web前端 > js教程 > 主體

jQuery封裝placeholder的實例程式碼

零下一度
發布: 2017-07-21 17:27:57
原創
1385 人瀏覽過

頁面中的輸入框預設的提示文字一般使用placeholder屬性就可以了,即:

<input type="text" name="username" placeholder="请输入用户名" value="" id="username"/>
登入後複製

最多加點樣式控制下預設文字的顏色

input::-webkit-input-placeholder{color:#AAAAAA;}
登入後複製

但是低版的瀏覽器卻不支援這個placeholder屬性,那麼真的要在低版瀏覽器也要實作跟placeholder 一樣的效果,就需要寫個插件來相容下,下面就細講一下怎樣用jquery來實現這個模擬效果。

實現這個模擬效果,頁面的一般呼叫方式:

$('input').placeholder();
登入後複製

#首先,先寫jquery外掛的一般結構:

;(function($){
    $.fn.placeholder = function(){//实现placeholder的代码    }
})(jQuery)
登入後複製

下面我們就要判斷瀏覽器是否支援placeholder屬性

;(function($){
    $.fn.placeholder = function(){this.each(function(){var _this = this;var supportPlaceholder = 'placeholder' in document.createElement('input');if(!supportPlaceholder){//不支持placeholder属性的操作}
        });
    }
})(jQuery)
登入後複製

我們要支援鍊式操作,如下:

;(function($){
    $.fn.placeholder = function(){         return this.each(function(){var _this = this;var supportPlaceholder = 'placeholder' in document.createElement('input');if(!supportPlaceholder){//不支持placeholder属性的操作}
        });
    }
})(jQuery)
登入後複製

預設組態項目:

options = $.extend({
    placeholderColor:'#aaaaaa',
    isSpan:false, //是否使用插入span标签模拟placeholder的方式,默认是不需要onInput:true //实时监听输入框},options);
登入後複製

#如果不需要透過span來模擬placeholder效果,那麼就需要透過輸入框的value值來判斷,如下程式碼:

if(!options.isSpan){
    $(_this).focus(function () {var pattern = new RegExp("^" + defaultValue + "$|^$");
        pattern.test($(_this).val()) && $(_this).val('').css('color', defaultColor);
    }).blur(function () {if($(_this).val() == defaultValue) {
            $(_this).css('color', defaultColor);
        }else if($(_this).val().length == 0) {
            $(_this).val(defaultValue).css('color', options.placeholderColor)
        }
    }).trigger('blur');
}
登入後複製

如果需要同span標籤來模擬placeholder效果,程式碼如下:

var $simulationSpan = $('<span class="wrap-placeholder">'+defaultValue+'</span>');
$simulationSpan.css({'position':'absolute','display':'inline-block','overflow':'hidden','width':$(_this).outerWidth(),'height':$(_this).outerHeight(),'color':options.placeholderColor,'margin-left':$(_this).css('margin-left'),'margin-top':$(_this).css('margin-top'),'padding-left':parseInt($(_this).css('padding-left')) + 2 + 'px','padding-top':_this.nodeName.toLowerCase() == 'textarea' ? parseInt($(_this).css('padding-top')) + 2 : 0,'line-height':_this.nodeName.toLowerCase() == 'textarea' ? $(_this).css('line-weight') : $(_this).outerHeight() + 'px','font-size':$(_this).css('font-size'),'font-family':$(_this).css('font-family'),'font-weight':$(_this).css('font-weight')
});//通过before把当前$simulationSpan添加到$(_this)前面,并让$(_this)聚焦$(_this).before($simulationSpan.click(function () {
    $(_this).trigger('focus');
}));//当前输入框聚焦文本内容不为空时,模拟span隐藏$(_this).val().length != 0 && $simulationSpan.hide();if (options.onInput) {//绑定oninput/onpropertychange事件var inputChangeEvent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange';
    $(_this).bind(inputChangeEvent, function () {
        $simulationSpan[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block';
    });
}else {
    $(_this).focus(function () {
        $simulationSpan.hide();
    }).blur(function () {/^$/.test($(_this).val()) && $simulationSpan.show();
    });
};
登入後複製

#整體程式碼:

;(function($){
    $.fn.placeholder = function(options){
        options = $.extend({
            placeholderColor:'#aaaaaa',
            isSpan:false, //是否使用插入span标签模拟placeholder的方式,默认是不需要onInput:true //实时监听输入框        },options);         return this.each(function(){var _this = this;var supportPlaceholder = 'placeholder' in document.createElement('input');if(!supportPlaceholder){//不支持placeholder属性的操作var defaultValue = $(_this).attr('placeholder');var defaultColor = $(_this).css('color');if(!options.isSpan){
                    $(_this).focus(function () {var pattern = new RegExp("^" + defaultValue + "$|^$");
                        pattern.test($(_this).val()) && $(_this).val('').css('color', defaultColor);
                    }).blur(function () {if($(_this).val() == defaultValue) {
                            $(_this).css('color', defaultColor);
                        }else if($(_this).val().length == 0) {
                            $(_this).val(defaultValue).css('color', options.placeholderColor)
                        }
                    }).trigger('blur');
                }else{var $simulationSpan = $('<span class="wrap-placeholder">'+defaultValue+'</span>');
                    $simulationSpan.css({'position':'absolute','display':'inline-block','overflow':'hidden','width':$(_this).outerWidth(),'height':$(_this).outerHeight(),'color':options.placeholderColor,'margin-left':$(_this).css('margin-left'),'margin-top':$(_this).css('margin-top'),'padding-left':parseInt($(_this).css('padding-left')) + 2 + 'px','padding-top':_this.nodeName.toLowerCase() == 'textarea' ? parseInt($(_this).css('padding-top')) + 2 : 0,'line-height':_this.nodeName.toLowerCase() == 'textarea' ? $(_this).css('line-weight') : $(_this).outerHeight() + 'px','font-size':$(_this).css('font-size'),'font-family':$(_this).css('font-family'),'font-weight':$(_this).css('font-weight')
                    });//通过before把当前$simulationSpan添加到$(_this)前面,并让$(_this)聚焦$(_this).before($simulationSpan.click(function () {
                        $(_this).trigger('focus');
                    }));//当前输入框聚焦文本内容不为空时,模拟span隐藏$(_this).val().length != 0 && $simulationSpan.hide();if (options.onInput) {//绑定oninput/onpropertychange事件var inputChangeEvent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange';
                        $(_this).bind(inputChangeEvent, function () {
                            $simulationSpan[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block';
                        });
                    }else {
                        $(_this).focus(function () {
                            $simulationSpan.hide();
                        }).blur(function () {/^$/.test($(_this).val()) && $simulationSpan.show();
                        });
                    };
                }
            }
        });
    }
})(jQuery);
登入後複製

呼叫方式,需要透過span標籤來模擬的話:

$("#username").placeholder({
    isSpan:true});
登入後複製

 

以上是jQuery封裝placeholder的實例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!