码迷,mamicode.com
首页 > 其他好文 > 详细

日历控件源码

时间:2015-01-06 11:56:37      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:日历   控件   javascript   源码   

前两天需要个简单的日历控件,网上搜了一下居然还有人卖,估计是提供其他维护服务吧,反正我是用不到的,自己手写了个凑合用,自己写的兼容性没测过,如果有什么问题大家给点改进意见。

先上图

技术分享

源码

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>

    <script type="text/javascript">

        //星期列表
        var WEEK = ["日","一","二","三","四","五","六"];
        //平年每月天数
        var DAYS_IN_NORMAL = [31,28,31,30,31,30,31,31,30,31,30,31];
        //闰年每月天数
        var DAYS_IN_SPECIAL = [31,29,31,30,31,30,31,31,30,31,30,31];
        //选择年份每月天数
        var DAYS_IN_SELECTED;
        //存放日期的输入框
        var CONTAINER;
        //日期分隔符
        var SPLIT;
        //日历界面
        var DATE_PANEL;
        //选定的日期,默认为当天
        var DEFAULT_DATE = new Date();

        /**
         * 日期控件入口,主要控制div层显示和隐藏
         * @param inputId 日期输入框ID
         * @param split   日期分隔符
         */
        function selectDate(inputId,split)
        {
            SPLIT = split;
            CONTAINER = document.getElementById(inputId);
            DATE_PANEL = document.getElementById("div_"+inputId);

            //获取日期输入框位置(x,y)
            var x = CONTAINER.clientLeft;
            var y = CONTAINER.clientTop + CONTAINER.clientHeight;
            var strDate = CONTAINER.value.trim();

            //设定日历的日期
            if(strDate != "")
            {
                var ymd = changeStr2ArrDate(strDate);

                if(ymd.length==3)
                {
                    DEFAULT_DATE.setFullYear(parseInt(ymd[0]));
                    DEFAULT_DATE.setMonth(parseInt(ymd[1])-1);
                    DEFAULT_DATE.setDate(parseInt(ymd[2]));
                }
                else
                {
                    alert("输入日期格式不正确");
                    return "";
                }
            }

            if(DATE_PANEL.style.display=="none")
            {
                DATE_PANEL.style.border = "1px solid black";
                DATE_PANEL.style.backgroundColor = "aliceblue";
                DATE_PANEL.style.width = "175px";
                DATE_PANEL.style.height = "160px";
                DATE_PANEL.style.position = "fixed";
                DATE_PANEL.style.zIndex = "99";
                DATE_PANEL.style.marginLeft = x;
                DATE_PANEL.style.marginTop = y;
                DATE_PANEL.innerHTML = datePanel();
                DATE_PANEL.style.display = "block";
            }
            else
            {
                DATE_PANEL.style.display = "none";
            }
        }

        /**
         * 将字符串日期转数组存储
         *
         * @param strDate
         * @returns {array} 三位长度数组,分别对应年月日
         */
        function changeStr2ArrDate(strDate)
        {
            var arr;
            if(SPLIT == "-" && strDate.substr(0,1) == "-")
            {
                arr =  strDate.substr(1).split(SPLIT);
                if(arr.length>1)
                {
                    arr[0] = "-" + arr[0];
                }
            }
            else
            {
                arr = strDate.split(SPLIT);
            }

            if(arr.length==3 && parseInt(arr[1])>0 &&  parseInt(arr[1]) < 13 && parseInt(arr[2])>0 &&  parseInt(arr[2]) <= parseInt(DAYS_IN_SELECTED[parseInt(arr[1])]))
            {
               return arr;
            }
            else
            {
                return new Array();
            }
        }

        /**
         * 根据输入字符串型日期,获取当月日历
         *
         * @param value
         * @returns {string}
         */
        function datePanel()
        {
            var html = "<table width='100%' id='date_table'>";
            html += menuTable();
            html += addWeekTitle();
            html += mainTable();
            html += "</table>";
            return html;
        }

        /**
         * 获取日历
         *
         * @returns {string}
         */
        function mainTable()
        {
            var year = DEFAULT_DATE.getFullYear();
            var month = DEFAULT_DATE.getMonth();
            var day = DEFAULT_DATE.getDate();
            var week = DEFAULT_DATE.getDay();

            getDaysInMonth(year);
            var currentMonthMap = getMonthMap(year,month);

            return transArr2Table(currentMonthMap);
        }

        /**
         * 设定给定年份的每月天数
         *
         * @param year
         */
        function getDaysInMonth(year)
        {
            if(year%400 == 0 || (year%4 ==0 && year%100!=0))
            {
                DAYS_IN_SELECTED = DAYS_IN_SPECIAL;
            }
            else
            {
                DAYS_IN_SELECTED = DAYS_IN_NORMAL;
            }
        }

        /**
         * 当月日历数组,包括空白部分
         *
         * @param year
         * @param month
         * @returns {Array}
         */
        function getMonthMap(year,month)
        {
            var first_day_in_week = new Date(year,month,1).getDay();
            var last_day_in_week = new Date(year,month,DAYS_IN_SELECTED[month]).getDay();
            var daysInThisMonth = DAYS_IN_SELECTED[month];
            var mapDays = first_day_in_week + DAYS_IN_SELECTED[month] + 6 - last_day_in_week;

            var map = new Array(mapDays);
            var count = 1;
            for(var i=0;i<mapDays;i++)
            {
                if(i<first_day_in_week)
                {
                    map[i] = "  ";
                }
                else if(i<=daysInThisMonth+first_day_in_week-1)
                {
                    map[i] = ""+count;
                    count++;
                }
                else
                {
                    map[i] = "  ";
                }
            }
            return map;
        }

        /**
         * 将数组转换成html图标
         *
         * @param currentMonthMap
         * @returns {string}
         */
        function transArr2Table(currentMonthMap)
        {
            var html = "";
            var rows = currentMonthMap.length/7;
            for(var i=0;i<rows;i++)
            {
                html += "<tr>";
                for(var n=0;n<7;n++)
                {
                    var num = n+i*7;
                    if(currentMonthMap[num]=="  ")
                    {
                        html += "<td id='td_"+num+"'>"+currentMonthMap[num]+"</td>";
                    }
                    else if(currentMonthMap[num]==DEFAULT_DATE.getDate())
                    {
                        //点击时日期,高亮显示
                        html += "<td id='td_"+num+"' onclick=\"chooseDate(this);\" ";
                        html += "style='font-size: 13px;background-color: palegreen;text-align:center;'>"
                        html += currentMonthMap[num];
                        html += "</td>";
                    }
                    else
                    {
                        //其他日期,鼠标经过事件,点击事件
                        html += "<td id='td_"+num+"' onmouseover=\"changeColor('td_"+num+"')\" ";
                        html += "onmouseout=\"resetColor('td_"+num+"')\" ";
                        html += "onclick=\"chooseDate(this);\" ";
                        html += "style='font-size: 13px;text-align:center;'>";
                        html += currentMonthMap[num];
                        html += "</td>";
                    }
                }
                html += "</tr>";
            }
            return html;
        }

        /**
         * 日期选择菜单
         *
         * @returns {string}
         */
        function menuTable()
        {
            var html = "<tr>";
            html += "<td colspan='7'>";
            html += "<input style='width: 20px;font-size: 10px;' type='button'value='<<' onclick='change(-1,0);'/>";
            html += "<input style='width: 20px;font-size: 10px;' type='button'value='<' onclick='change(0,-1)'/>";
            html += "<input style='width: 30px;style='font-size:10px;'' type='text'value='"+DEFAULT_DATE.getFullYear()+"' id='year' onchange=\"textChange()\"/>";
            html += "<label style='font-size:10px;'>年</label>";
            html += "<input style='width: 15px;style='font-size:10px;'' type='text' value='"+(DEFAULT_DATE.getMonth()+1)+"' id='month' onchange=\"textChange()\"/>";
            html += "<label style='font-size:10px;'>月</label>";
            html += "<input style='width: 20px;font-size: 10px;' type='button'value='>'onclick='change(0,1)'/>";
            html += "<input style='width: 20px;font-size: 10px;' type='button'value='>>' onclick='change(1,0);'/></td>";
            html += "</tr>";
            return html;
        }

        /**
         * 星期表头
         *
         * @returns {string}
         */
        function addWeekTitle()
        {
            var html = "<tr>"
            for(var i=0;i<7;i++)
            {
                html += "<td style='font-size: 13px;text-align:center;font-weight: bold;'>"+WEEK[i]+"</td>";
            }
            html += "</tr>";
            return html;
        }

        /**
         * 鼠标经过变色事件
         * @param id
         */
        function changeColor(id)
        {
            document.getElementById(id).style.backgroundColor = "pink";
        }

        /**
         * 鼠标移除还原颜色
         *
         * @param id
         */
        function resetColor(id)
        {
            document.getElementById(id).style.backgroundColor = "";
        }

        /**
         * 手动修改年月栏位
         */
        function textChange()
        {
            var year = document.getElementById("year");
            var month = document.getElementById("month");

            updateDateTable(year.value,month.value);
        }

        /**
         * 点击修改年月
         *
         * @param yearChange
         * @param monthChange
         */
        function change(yearChange,monthChange)
        {
            var year = document.getElementById("year");
            var month = document.getElementById("month");
            year.value = parseInt(year.value) + yearChange;
            month.value =  parseInt(month.value)+ monthChange;

            updateDateTable(year.value,month.value);
        }

        /**
         * 更新日历
         *
         * @param year
         * @param month
         */
        function updateDateTable(year,month)
        {
            DEFAULT_DATE.setFullYear(parseInt(year));
            DEFAULT_DATE.setMonth(parseInt(month)-1);
            DEFAULT_DATE.setDate(DEFAULT_DATE.getDate());

            DATE_PANEL.innerHTML = datePanel();
        }

        /**
         * 选定日期
         *
         * @param td
         */
        function chooseDate(td)
        {
            var day = td.innerHTML;
            var year = document.getElementById("year").value;
            var month = document.getElementById("month").value;

            CONTAINER.value = year+SPLIT+month+SPLIT+day;
            DATE_PANEL.style.display = "none";
        }
    </script>
</head>
<body>
    <!--
        使用说明:
            div的id格式为 div_输入框的ID
            selectDate的第一个参数为输入框的ID,第二个参数为日期分隔符,必须输入

            已有校验:
                年份不做校验,负数为公元前
                月份为1-12
                日期为当月有效天数
    -->
    <input type="text" id="date1"/>
    <div id="div_date1" style="display:none;"></div>
    <input type="button" value="选择" onclick="selectDate('date1','-');"/>
</body>
</html>


日历控件源码

标签:日历   控件   javascript   源码   

原文地址:http://blog.csdn.net/sunshoupo211/article/details/42455957

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!