当前位置:   article > 正文

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

js自定义月份选择器

这里笔者制作了一个简单还算美观的月份选择器,来实现年月份随意选择的需求。
实际开发中可能会碰到这样的需求,只需要选择年月份就可以,不需要其他日期,时间等的选择,有些日期了的插件较大,杀猪焉用宰牛刀,没必要去引用那些东西,所以笔者就自己编写了一个简单的月份选择插件。先看效果图:
这里写图片描述
下面是插件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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

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

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

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/306575
推荐阅读
相关标签
  

闽ICP备14008679号