jquery日历控件实现方法分享


Posted in Javascript onMarch 07, 2014

注释掉的是默认的css样式,你可以修改成自己的样式实现另一个风格,大家参考使用吧

/**
 * jQuery Calendar Plugin
 */
(function($, window) {
    'use strict';
    $.fn.calendar = function(options) {
        //check is select, if nothing select, return this
        if (!this.length) {
            if (options && options.debug && window.console) {
                console.log("nothing select");
            }
            return this;
        }
        var self = $(this);
        // default parameter setting
        var defaults = {
            cssPath: '', //user-define loading path of css file
            eventName: 'click', //user-define the event name that triggers the control
            onSelectDate: null, //callback function after select date
            autoClose: false
        };
        //inherit user-defined parameter
        defaults = $.extend(defaults, options);
        //default as data of the day
        var d_date = new Date();
        var _date = {
            year: d_date.getFullYear(),
            month: d_date.getMonth() + 1,
            day: d_date.getDate(),
            week: d_date.getDay()
        };
        //default template of plugin
        var calendarDiv = '<div id="calendar" class="cld_grid" style="display:none;z-index:100;">';
        calendarDiv += '<div id="calendar_year_month" class="cld_year_month" style="position:relative;">';
        calendarDiv += '<div id="last-year" style="position:absolute;left:30px;"><</div>';
        calendarDiv += '<div id="last-month" style="position:absolute;left:60px;"><<</div>';
        calendarDiv += '<div id="next-year" style="position:absolute;right:30px;">></div>';
        calendarDiv += '<div id="next-month" style="position:absolute;right:60px;">>></div>';
        calendarDiv += '<input style="width:40px;text-align:center;" type="text" id="calendar_year" value="' + _date.year + '">-<input style="width:25px;text-align:center;" type="text" id="calendar_month" value="' + _date.month + '"></div>'
        calendarDiv += '<div id="calendar_week_box" class="cld_week_box clearfix">';
        calendarDiv += '<div class="header-day" data-index = "0">日</div>';
        calendarDiv += '<div class="header-day" data-index = "1">一</div>';
        calendarDiv += '<div class="header-day" data-index = "2">二</div>';
        calendarDiv += '<div class="header-day" data-index = "3">三</div>';
        calendarDiv += '<div class="header-day" data-index = "4">四</div>';
        calendarDiv += '<div class="header-day" data-index = "5">五</div>';
        calendarDiv += '<div class="header-day" data-index = "6">六</div>';
        calendarDiv += '</div>';
        calendarDiv += '<div class="days clearfix">';
        for (var k = 0; k < 35; k++) {
            calendarDiv += '<div class="day"><span class="day-number">' + '' + '</span></div>';
        }
        calendarDiv += '</div></div>';
        var calendarAction = {
            //initialization
            initAction: function() {
                calendarAction.thisClick();
                calendarAction.inputChange();
                calendarAction.buttonChange();
                calendarAction.chooseDate();
            },
            //click to display
            thisClick: function() {
                self.bind(defaults.eventName, function(e) {
                    calendarAction.showCalendar();
                });
            },
            //when year and month in the input box changes
            inputChange: function() {
                $('#calendar_year, #calendar_month').bind('change', function() {
                    var year = $('#calendar_year').val(),
                        month = $('#calendar_month').val();
                    if (!/^\d{4}$/.test(year)) {
                        alert('please input four-digit year');
                        return false;
                    }
                    if (!/^\d{1,2}$/.test(month) || (month > 12 || month <= 0)) {
                        alert('please input proper month');
                        return false;
                    }
                    //Initialize after year and month changes
                    init_day_numbers(year, month);
                });
            },
            //click to change year and month
            buttonChange: function() {
                $('#last-year').bind('click', function() {
                    var lastYear = parseInt($('#calendar_year').val()) - 1 > 0 ? parseInt($('#calendar_year').val()) - 1 : 1;
                    $('#calendar_year').val(lastYear);
                    init_day_numbers(lastYear, $('#calendar_month').val());
                });
                $('#last-month').bind('click', function() {
                    var lastMonth = parseInt($('#calendar_month').val()) - 1 > 0 ? parseInt($('#calendar_month').val()) - 1 : 12,
                        thisYear = lastMonth == 12 ? parseInt($('#calendar_year').val()) - 1 : $('#calendar_year').val();
                    $('#calendar_month').val(lastMonth);
                    $('#calendar_year').val(thisYear);
                    init_day_numbers(thisYear, lastMonth);
                });
                $('#next-year').bind('click', function() {
                    var nextYear = parseInt($('#calendar_year').val()) + 1;
                    $('#calendar_year').val(nextYear);
                    init_day_numbers(nextYear, $('#calendar_month').val());
                });
                $('#next-month').bind('click', function() {
                    var nextMonth = parseInt($('#calendar_month').val()) + 1 <= 12 ? parseInt($('#calendar_month').val()) + 1 : 1,
                        thisYear = nextMonth == 1 ? parseInt($('#calendar_year').val()) + 1 : $('#calendar_year').val();
                    $('#calendar_month').val(nextMonth);
                    $('#calendar_year').val(thisYear);
                    init_day_numbers(thisYear, nextMonth);
                });
            },
            //set the relative offset between control and webpage, then display
            showCalendar: function() {
                var o_x = self.offset().left,
                    o_y = self.offset().top + self[0].offsetHeight;
                $('#calendar').css({
                    'position': 'absolute',
                    'left': o_x,
                    'top': o_y,
                    'display': 'block'
                });
            },
            //close plugin
            closeCalendar: function() {
                $('#calendar').hide();
            },
            //select date
            chooseDate: function() {
                $('.day').live('click', function() {
                    var _date = $(this).attr('data-date');
                    //trigger callback function
                    if ($.isFunction(defaults.onSelectDate)) {
                        defaults.onSelectDate.call(this, _date);
                    }
                    if (defaults.autoClose) {
                        calendarAction.closeCalendar();
                    }
                });
            }
        };
        //write calendar template in webpage
        $('body').append(calendarDiv);
        //initialize the year, month, day of calendar list
        init_day_numbers(_date.year, _date.month);
        //initialize plugin action
        calendarAction.initAction();
        function init_day_numbers(year, month) {
            var maxday = getmaxDay(year, month),
                firstWeek,beforeNumber,
                startIndex = beforeNumber = firstWeek = getFirstWeek(year, month),
                afterNumber = 35 - maxday - beforeNumber,
                lastMonthMaxDay = getMaxDayByLastMonth(year, month),
                nextMonthMaxDay = getMaxDayByNextMonth(year, month),
                Edge = getLastAndNextDate(year, month);
            var default_html = '';
            for (var k = 0; k < 35; k++) {
                default_html += '<div class="day"><span class="day-number">' + '' + '</span></div>';
            };
            $('.days').html(default_html);
            for (var s = 1; s <= maxday; s++) {
                $('.day-number').eq(startIndex).text(s);
                $('.day').eq(startIndex).attr('data-date', year + '-' + month + '-' + s);
                if (s == _date.day && year == _date.year && month == _date.month) {
                    $('.day').eq(startIndex).addClass('today');
                }
                startIndex++;
            };
            for (var k = 0; k < beforeNumber; k++) {
                var realDay = lastMonthMaxDay - beforeNumber + k + 1;
                $('.day-number').eq(k).text(realDay);
                $('.day-number').eq(k).addClass('last-month');
                $('.day').eq(k).attr('data-date', Edge.lastY + '-' + Edge.lastM + '-' + realDay);
            };
            for (var l = 1; l <= afterNumber; l++) {
                var _index = beforeNumber + maxday + (l - 1);
                $('.day-number').eq(_index).text(l);
                $('.day-number').eq(_index).addClass('next-month');
                $('.day').eq(_index).attr('data-date', Edge.nextY + '-' + Edge.nextM + '-' + l);
            }
        }
        function getLastAndNextDate(year, month) {
            var lastM = month - 1 > 0 ? month - 1 : 12,
                lastY = lastM == 12 ? year - 1 : year,
                nextM = month + 1 > 12 ? 1 : month + 1,
                nextY = nextM == 1 ? year + 1 : year;
            return {
                lastM: lastM,
                lastY: lastY,
                nextM: nextM,
                nextY: nextY
            };
        }
        //obtain what the first day of one month is in a week
        function getFirstWeek(year, month) {
            var date = new Date(year, month - 1, 1);
            return date.getDay();
        }
        //obtain the year, month, day of today
        function getToday() {
            var date = new Date();
            return today = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getDay()];
        }
        //obtain the number of days for a month
        function getmaxDay(year, month) {
            var date = new Date(year, month, 0);
            return date.getDate();
        }
        //obtain the number of days for last month
        function getMaxDayByLastMonth(year, month) {
            month = month - 1 <= 0 ? 12 : month - 1;
            year = month == 12 ? year - 1 : year;
            return getmaxDay(year, month);
        }
        //obtain the number of days for next month
        function getMaxDayByNextMonth(year, month) {
            month = month + 1 > 12 ? 1 : month + 1;
            year = month == 1 ? year + 1 : year;
            return getmaxDay(year, month);
        }
        //obtain the days list of a certain year and month, return array
        function getDayList(year, month) {
            var _list = [],
                maxday = getmaxDay(year, month),
                month = month - 1;
            for (var i = 1; i <= maxday; i++) {
                var d = new Date(year, month, i);
                _list[i - 1] = d.getDay();
            }
            return _list;
        }
    }
})(jQuery, window);
/*
<style type="text/css">
        *{margin:0;padding:0;font-size:12px;font-family: Inconsolata, Monaco, 'Andale Mono', Courier;}
        .cld_grid{width:300px;margin:auto;}
        .cld_week_box{background-color:#3883a3;width:100%;}
        .header-day{float: left;padding: 10px 0px;width: 14.2857%;text-align: center;color: white;font-family:'微软雅黑'}
        .clearfix:after{content: ".";display: block;clear: both;visibility: hidden;line-height: 0;height: 0;}
        .day{float: left;
            width: 14.2857%;
            height: 13px;
            padding: 10px 0;
            text-align: center;
            color: #4f4f4f;
            background-color: #ebebeb;
            border-bottom: 2px solid white;
            background-image: url('http://kylestetz.github.io/CLNDR/css/./triangle.svg');
            background-size: cover;
            background-position: center;
            cursor: pointer;
        }
        .days .last-month, .days .next-month {
            opacity: 0.3;
        }
        .days .today{
            background:#fff;
        }
        .cld_year_month{   
            padding: 10px;
            background-color: #71bbd2;
            text-align: center;
            color: white;
            letter-spacing: 1px;
            font-size:14px;
        }
        .cld_year_month div{cursor:pointer;}
    </style>
*/
Javascript 相关文章推荐
js计算页面刷新的次数
Jul 20 Javascript
Javascript 继承机制的实现
Aug 12 Javascript
js 处理URL实用技巧
Nov 23 Javascript
裁剪字符串trim()自定义改进版
Apr 10 Javascript
JQuery与Ajax调用新浪API获取短网址的代码
Feb 07 Javascript
自己使用jquery写的一个无缝滚动的插件
Apr 30 Javascript
js方法数据验证的简单实例
Sep 17 Javascript
Easyui笔记2:实现datagrid多行删除的示例代码
Jan 14 Javascript
利用JS对iframe父子(内外)页面进行操作的方法教程
Jun 15 Javascript
开发用到的js封装方法(20种)
Oct 12 Javascript
微信小程序之swiper滑动面板用法示例
Dec 04 Javascript
小程序实现层叠卡片滑动效果
Aug 26 Javascript
jquery.form.js用法之清空form的方法
Mar 07 #Javascript
jquery设置按钮停顿3秒不可用
Mar 07 #Javascript
jquery 实现两级导航菜单附效果图
Mar 07 #Javascript
document.addEventListener使用介绍
Mar 07 #Javascript
开发中可能会用到的jQuery小技巧
Mar 07 #Javascript
javascript匿名函数应用示例介绍
Mar 07 #Javascript
js登录弹出层特效
Mar 07 #Javascript
You might like
php中数据的批量导入(csv文件)
2006/10/09 PHP
PHP5中的时间相差8小时的解决办法
2008/03/28 PHP
如何在旧的PHP系统中使用PHP 5.3之后的库
2015/12/02 PHP
javascript 常用方法总结
2009/06/03 Javascript
扩展jquery实现客户端表格的分页、排序功能代码
2011/03/16 Javascript
基于jQuery的可用于选项卡及幻灯的切换插件
2011/03/28 Javascript
jQuery函数map()和each()介绍及异同点分析
2014/11/08 Javascript
jQuery实现仿Alipay支付宝首页全屏焦点图切换特效
2015/05/04 Javascript
深入解析JavaScript的闭包机制
2015/10/20 Javascript
JS实现在状态栏显示打字效果完整实例
2015/11/02 Javascript
jQuery qrcode生成二维码的方法
2016/04/03 Javascript
jQuery插件HighCharts绘制的2D堆柱状图效果示例【附demo源码下载】
2017/03/14 Javascript
Bootstrap模态框插入视频的实现代码
2017/06/25 Javascript
详解Angular Reactive Form 表单验证
2017/07/06 Javascript
JavaScript实现重力下落与弹性效果的方法分析
2017/12/20 Javascript
官方推荐react-navigation的具体使用详解
2018/05/08 Javascript
Vue.js获取手机系统型号、版本、浏览器类型的示例代码
2020/05/10 Javascript
[01:28:31]《加油DOTA》真人秀 第五期
2014/09/01 DOTA
Python聚类算法之DBSACN实例分析
2015/11/20 Python
Python编程之基于概率论的分类方法:朴素贝叶斯
2017/11/11 Python
Python实现的根据文件名查找数据文件功能示例
2018/05/02 Python
python模块之subprocess模块级方法的使用
2019/03/26 Python
pandas.read_csv参数详解(小结)
2019/06/21 Python
Python爬虫运用正则表达式的方法和优缺点
2019/08/25 Python
python实现用户名密码校验
2020/03/18 Python
通过实例解析Python文件操作实现步骤
2020/09/21 Python
澳大利亚快时尚鞋类市场:Billini
2018/05/20 全球购物
中英文自我评价常用句型
2013/12/19 职场文书
乱丢垃圾袋检讨书
2014/10/08 职场文书
党员检讨书
2014/10/13 职场文书
周年庆典答谢词
2015/01/20 职场文书
2015年禁毒宣传活动总结
2015/03/25 职场文书
公务员处分决定书
2015/06/25 职场文书
公司保密管理制度
2015/08/04 职场文书
大学生社会服务心得体会
2016/01/22 职场文书
人事行政部各岗位职责说明书!
2019/07/15 职场文书