回忆之placeholder

直接看效果点这里

HTML

<!DOCTYPE html>
<html>
<head lang="zh-CN">
    <meta charset="utf-8">
    <title> Placeholder </title>
</head>
<body>
<input class="J_Placeholder" type="text" value=""/>
<textarea class="J_Placeholder"></textarea>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script src="jquery.placeholder.js"></script>
<script>
$('.J_Placeholder').placeholder({
    'txt': '请输入提示信息'
});
</script>
</body>
</html>
View Code

JS

/**
 * @description: 表单input、textarea占位提示
 * @author:jununx@gmail.com
 * @update: 2014/11/10
 *
 * @param txt{string} 提示信息语句
 *
 * 用法
 *
 * $('.J_Placeholder').placeholder({
 *     'txt': '请输入提示信息'
 * });
 */

;(function($){

    var methods = {
        init: function(opts){
            this.isHtml5Placeholder() ? this.changeHtml5Placeholder(opts) : this.changePlaceholder(opts);
        },
        isHtml5Placeholder: function(){
            var res = 'placeholder' in document.createElement('input');
            return res;
        },
        changePlaceholder: function(opts){
            opts.that.attr('value') == '' && opts.that.attr({
                'value': opts.txt
            });

            opts.that
                .on('focus', function(){
                    if($(this).val() === opts.txt){
                        $(this).attr('value', '');
                    }
                })
                .on('blur', function(){
                    if($(this).val() == ''){
                        $(this).attr({
                            'value': opts.txt
                        });
                    }
                });
        },
        changeHtml5Placeholder: function(opts){
            opts.that.attr({
                'placeholder': opts.txt
            });
        }
    };

    $.fn.placeholder = function(opts){
        opts = $.extend({
            'that': this,
            'txt': ''
        }, opts || {});
        methods.init(opts);
        return this;
    };

})(jQuery);
原文地址:https://www.cnblogs.com/jununx/p/4472909.html