自定义一个月份选择器插件

来源:互联网 发布:手机如何清除数据 编辑:程序博客网 时间:2024/05/29 16:59

这里笔者制作了一个简单还算美观的月份选择器,来实现年月份随意选择的需求。
实际开发中可能会碰到这样的需求,只需要选择年月份就可以,不需要其他日期,时间等的选择,有些日期了的插件较大,杀猪焉用宰牛刀,没必要去引用那些东西,所以笔者就自己编写了一个简单的月份选择插件。先看效果图:
这里写图片描述
下面是插件js源码:

(function($) {    var MonthPicker = function(dom, options) {        this.$dom = dom,            this.defaults = {                currentYear: '',            },            this.opts = $.extend({}, this.defaults, options)    }    /**     * 添加渲染页面和数据的方法     * */    MonthPicker.prototype = {        renderMonthPicker: function() {            var self = this;            this.$dom.focus(function(event) {                self.opts.currentYear = new Date().getFullYear();                $('body').find('.mp-month-picker-box').empty().remove();                $('body').append('<div class="mp-month-picker-box" style="left:' + $(this).position().left + 'px;top:' + ($(this).position().top + 40) + 'px;">' +                    '<i></i>' +                    '<div class="mp-year-picker">' +                    '<div class="mp-prev-year"><i></i><i></i></div>' +                    '<span>' + self.opts.currentYear + '</span>' +                    '<div class="mp-next-year"><i></i><i></i></div>' +                    '</div>' +                    '<ul class="mp-month-picker">' +                    '<li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li>' +                    '</ul>' +                    '</div>');            })        },        handleClick: function() {            var self = this;            this.$dom.blur(function() {                var innerSelf = this;                $('div.mp-prev-year').click(function() {                    $(this).next().html(--self.opts.currentYear);                })                $('div.mp-next-year').click(function() {                    $(this).prev().html(++self.opts.currentYear);                })                $('ul.mp-month-picker li').click(function(event) {                    var value = self.opts.currentYear + '-' + $(this).html();                    $(innerSelf).val(value);                    $(this).parent().parent().empty().remove();                })            })        },        constructor: MonthPicker    };    $.fn.MonthPicker = function(options) {        var monthPicker = new MonthPicker(this, options);        monthPicker.renderMonthPicker();        monthPicker.handleClick();        return this.each(function() {});    }})(jQuery)

使用的时候,需要配合input输入框一起使用,示例如下:

$('#startTime').MonthPicker();

具体的样式表现,笔者就不在这里进行说明了,感兴趣的读者可以直接去下方的连接去下载。

github源码链接
csdn资源下载链接

阅读全文
0 0
原创粉丝点击