Jquery簡單的placeholder效果


Jquery簡單的placeholder效果

  由於IE6-IE9不支持HTML5中的placeholder,所以自己依賴於Jquery簡單的寫了一個,供參考!

  先看看效果吧!如下JSFiddle地址

 查看效果鏈接

JS代碼如下:

/*
 * JS placeholder
 * IE6-IE9不支持HTML5中的placeholder
 */
    
function Placeholder(options) {
    this.config = {
        defaultColor: '#ccc',
        curColor: '#333',
        targetElem: '.placeholderCls'
    };

    this.init(options);
}

Placeholder.prototype = {

    constructor:Placeholder,

    init: function(options){
        this.config = $.extend(this.config, options || {});
        var self = this,
            _config = self.config;
        
        $(_config.targetElem).each(function(){
            var supportPlaceholder = 'placeholder' in document.createElement('input');
            if(!supportPlaceholder) {
                var defaultValue = $(this).attr('placeholder');
                $(this).focus(function(){
                    var pattern = new RegExp("^" + defaultValue + "$|^$");
                    pattern.test($(this).val()) && $(this).val('').css('color',_config.curColor);
                }).blur(function(){
                    if($(this).val() == defaultValue) {
                        $(this).css('color',_config.defaultColor);
                    }else if($(this).val().length == 0){
                        $(this).val(defaultValue).css('color', _config.defaultColor);
                    }
                }).trigger('blur');
            }
        });
        
    }    
};
    

HTML代碼如下:

<form id="form1">
    <h3>通過value方式模擬placeholder</h3>
        
    <p>
        <label for="username1">用戶名:</label>
        <input type="text" class="placeholderCls" placeholder="請輸入用戶名">
    </p>
    <p>
        <label for="address1">地 址:</label>
        <input type="text" class="placeholderCls" placeholder="請輸入地址">
    </p>
    <p>
        <label for="remarks1">備 注:</label>
        <textarea placeholder="請輸入備注" class="placeholderCls"></textarea>
    </p>
</form>

代碼初始化:

<script>
    new Placeholder({});
</script>

 

 

 


免責聲明!

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



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