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 相关文章推荐
背景音乐每次刷新都可以自动更换
Feb 01 Javascript
JavaScript 异步方法队列链实现代码分析
Jun 05 Javascript
flexigrid 类似ext grid的JS表格代码
Jul 17 Javascript
javascript学习笔记(十八) 获得页面中的元素代码
Jun 20 Javascript
JS中图片缓冲loading技术的实例代码
Aug 29 Javascript
JavaScript拆分字符串时产生空字符的解决方案
Sep 26 Javascript
JavaScript 动态加载脚本和样式的方法
Apr 13 Javascript
JS封装cookie操作函数实例(设置、读取、删除)
Nov 17 Javascript
原生js实现移动端瀑布流式代码示例
Dec 18 Javascript
JavaScript编写带旋转+线条干扰的验证码脚本实例
May 30 Javascript
利用canvas实现的加载动画效果实例代码
Jul 05 Javascript
基于jQuery Easyui实现登陆框界面
Jul 10 jQuery
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分多步骤填写发布信息的简单方法实例代码
2012/09/23 PHP
php写入文件不覆盖的实例讲解
2019/09/17 PHP
javascript引用对象的方法代码
2007/08/13 Javascript
一个轻量级的javascript库 pj介绍
2010/12/19 Javascript
15条JavaScript最佳实践小结
2013/08/09 Javascript
jQuery向后台传入json格式数据的方法
2015/02/13 Javascript
JS实现网页背景颜色与select框中颜色同时变化的方法
2015/02/27 Javascript
nodejs中的fiber(纤程)库详解
2015/03/24 NodeJs
基于jQuery实现Div窗口震动特效代码-代码简单
2015/08/28 Javascript
JS自动倒计时30秒后按钮才可用(两种场景)
2015/08/31 Javascript
JavaScript sort数组排序方法和自我实现排序方法小结
2016/06/06 Javascript
js插件Jcrop自定义截取图片功能
2016/10/14 Javascript
webuploader模态框ueditor显示问题解决方法
2016/12/27 Javascript
zTree实现节点修改的实时刷新功能
2017/03/20 Javascript
vue.js实现含搜索的多种复选框(附源码)
2017/03/23 Javascript
vue-cli 如何打包上线的方法示例
2018/05/08 Javascript
vue路由结构可设一层方便动态添加路由操作
2020/08/31 Javascript
[01:23]2019完美世界全国高校联赛(春季赛)合肥全国总决赛
2019/06/10 DOTA
[07:37]DOTA2-DPC中国联赛2月2日Recap集锦
2021/03/11 DOTA
Python greenlet实现原理和使用示例
2014/09/24 Python
[原创]使用豆瓣提供的国内pypi源
2017/07/02 Python
学习python中matplotlib绘图设置坐标轴刻度、文本
2018/02/07 Python
pandas.DataFrame选取/排除特定行的方法
2018/07/03 Python
详解Python中字符串前“b”,“r”,“u”,“f”的作用
2019/12/18 Python
Python chardet库识别编码原理解析
2020/02/18 Python
施华洛世奇美国官网:SWAROVSKI美国
2018/02/08 全球购物
Club Monaco加拿大官网:设计师男女服装
2019/09/29 全球购物
枚举与#define宏的区别
2014/04/30 面试题
学子宴答谢词
2014/01/25 职场文书
阳光体育活动总结
2014/04/30 职场文书
大学生活动总结模板
2014/07/02 职场文书
乡镇保密工作责任书
2014/07/28 职场文书
开发房地产协议书
2014/09/14 职场文书
高中班主任培训心得体会
2016/01/07 职场文书
十个Python自动化常用操作,即拿即用
2021/05/10 Python
使用 Apache 反向代理的设置技巧
2022/01/18 Servers