javascript实例学习之六—自定义日历控件

时间:2024-03-10 13:12:38

基于之前上篇博客轻量级jquery,tool.js和base.js。自定义开发的base_datePicker插件,效果类似于jquery_ui的datePicker插件

//基于Base.js以及tool.js做的日历插件
$().extend(\'datePicker\', function() {
    //生成日历插件
    var $yearSpan;
    var $monthSpan;
    var tds;
    var $prevBtn;
    var $nextBtn;
    var $lastTr;
    var $datePicker;
    for (var i = 0, len = this.elements.length; i < len; i++) {
        var curElem = this.elements[i];
        $(curElem).focus(function() {
            $this = $(this);
            if (!this.datePicker) {
                var top = $this.top() + $this.height();
                var left = $this.left();
                this.datePicker = createDatePicker(top, left);
                $(this.datePicker).insertAfter(this);
                $datePicker = $(this.datePicker);
                $yearSpan = $(\'.myDatePicker .year\');
                $monthSpan = $(\'.myDatePicker .month\');
                $prevBtn = $(\'.myDatePicker .title .l\');
                $nextBtn = $(\'.myDatePicker .title .r\');
                tds = $(\'.myDatePicker\').getElem(0).getElementsByTagName(\'td\');
                //为上一月下一月的按钮添加点击事件
                addEventForBtn();
                //为表格的单元格添加点击事件
                addEventForTds(curElem);
                //在页面除日期输入框的任何地方点击,日历控件消失
                addEventForDocument(curElem);
            }
            $datePicker.show();
            var nowDate = new Date();
            refreshDate(nowDate.getFullYear(), nowDate.getMonth() + 1);
            //将当前的日期标注为红色
            showColor();

        });
        $(curElem).blur(function() {
            if (this.datePicker) {
                // $(this.datePicker).hide();
            }
        });
    }



    function createDatePicker(top, left) {
        var oDiv = document.createElement(\'div\');
        oDiv.style.position = \'absolute\';
        oDiv.style.top = top;
        oDiv.style.left = left;
        oDiv.className = \'myDatePicker\';
        var titleDiv = document.createElement(\'div\');
        titleDiv.className = \'title\';
        titleDiv.innerHTML = \'<span class="l"><</span> <span class = "year"></span>年<span class="month"></span > 月  <span class = "r" >> </span>\';
        oDiv.appendChild(titleDiv);
        var dateTable = document.createElement(\'table\');
        //生成表头的星期
        var dayArr = [\'周一\', \'周二\', \'周三\', \'周四\', \'周五\', \'周六\', \'周日\'];
        var thead = document.createElement(\'thead\');
        thead.insertRow(0);
        for (var i = 0, len = dayArr.length; i < len; i++) {
            var th = document.createElement(\'th\');
            th.innerHTML = dayArr[i];
            if (i == 5 || i == 6) {
                th.className = \'red\';
            }
            thead.rows[0].appendChild(th);
        }
        oDiv.appendChild(thead);
        //生成表格主体,6行七列
        var tbody = document.createElement(\'tbody\');
        for (var i = 0; i < 6; i++) {
            tbody.insertRow(i);
            for (j = 0; j < 7; j++) {
                tbody.rows[i].insertCell(j);
            }
        }
        oDiv.appendChild(tbody);
        //刷新数据

        return oDiv;
    }

    function isLeapYear(year) {
        if (year % 400 == 0) {
            return true;
        }
        if (year % 4 == 0 && year % 100 != 0) {
            return true;
        }
        return false;
    }

    function getDayNum(year, month) {
        var dayNum = 30;
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            dayNum = 31;
        } else
        if (month == 2 && isLeapYear(year)) {
            dayNum = 29;
        } else if (month == 2) {
            dayNum = 28;
        }
        return dayNum;
    }
    //根据年份和月份更新日历
    function refreshDate(year, month) {
        $yearSpan.html(year);
        $monthSpan.html(month);
        //生成日期数据
        var curDate = new Date();
        curDate.setFullYear(year);
        curDate.setMonth(month - 1);
        curDate.setDate(1);
        //当前的日历数据
        //getDay():0代表周日,1代表周一,...以此类推
        var xingqi = curDate.getDay();
        var index = xingqi - 1;
        if (xingqi == 0) {
            index = 6;
        }
        var dayNum = getDayNum(year, month);
        //首先将所有的td清空
        for (var i = 0; i < tds.length; i++) {
            tds[i].style.display = \'\';
            tds[i].className = \'\';
            tds[i].innerHTML = \'\';
        }

        //需要知道当月的天数
        var ri = 1;
        for (var i = index; i < index + dayNum; i++) {
            tds[i].innerHTML = ri;
            ri++;
        }
        //如果最后以行没有显示,则隐藏该行
        var hasContent = false;
        for (var len = tds.length - 1, i = len; i > len - 7; i--) {
            if (tds[i].innerHTML) {
                hasContent = true;
                break;
            }
        }
        if (!hasContent) {
            for (var len = tds.length - 1, i = len; i > len - 7; i--) {
                tds[i].style.display = \'none\';
            }
        }
    }
    //将当前的日期标注为红色
    function showColor() {
        var curYear = $yearSpan.html();
        var curMonth = $monthSpan.html();
        var nowDate = new Date();
        if (!(nowDate.getFullYear() == curYear && nowDate.getMonth() == (curMonth - 1))) {
            return;
        }
        for (var i = 0; i < tds.length; i++) {
            if (tds[i].innerHTML == nowDate.getDate()) {
                tds[i].className = \'red\';
                return;
            }
        }
    }
    //为向左向右的按钮添加点击事件
    function addEventForBtn() {
        $prevBtn.click(function() {
            var showYear = parseInt($yearSpan.html());
            var showMonth = parseInt($monthSpan.html());
            var prevMonth = showMonth - 1;
            var prevYear = showYear;
            if (showMonth == 1) {
                prevMonth = 12;
                prevYear = showYear - 1;
            }
            refreshDate(prevYear, prevMonth);
            showColor();
        });
        $nextBtn.click(function() {
            var showYear = parseInt($yearSpan.html());
            var showMonth = parseInt($monthSpan.html());
            var nextYear = showYear;
            var nextMonth = showMonth + 1;
            if (showMonth == 12) {
                nextMonth = 1;
                nextYear = showYear + 1;
            }
            refreshDate(nextYear, nextMonth);
            showColor();
        });
    }

    function addEventForTds(curElem) {
        for (var i = 0; i < tds.length; i++) {
            $(tds[i]).click(function() {
                if (this.innerHTML) {
                    var showYear = $yearSpan.html();
                    var showMonth = $monthSpan.html();
                    var showDate = this.innerHTML;
                    curElem.value = showYear + \'-\' + showMonth + \'-\' + showDate;
                    $datePicker.hide();
                }
            });
        }
    }

    function addEventForDocument(curElem) {
        $(document).click(function(e) {
            if(e.target!=curElem){
              if ($datePicker && $datePicker.isVisible()) {
                $datePicker.hide();
            }  
            }
            
        });

    }
});

依赖的css文件,myDatePicker.css

.myDatePicker{
    width:260px;
    margin-top:5px;
}
.myDatePicker th,
td {
    padding:5px;
    border: 1px solid #ccc;
    text-align: center;
    vertical-align: middle;
    font-size:10px;   

}
.myDatePicker td{
    cursor:pointer;
}

.myDatePicker .title {
    background: #135;
    height: 30px;
    line-height: 30px;
    color: #fff;
    padding: 0 10px;
    text-align: center;
    overflow: hidden;
    font-size:14px;
    letter-spacing: 1px;
    font-weight: 550;
}
.myDatePicker table{
    border-collapse:collapse;
    border-spacing: 0;

}
.myDatePicker .l{
    float:left;
    cursor:pointer;
}
.myDatePicker .r{
    float:right;
    cursor: pointer;
}
.myDatePicker .red{
    color:red;
}
.myDatePicker .blue{
    color:blue;
}

用法示例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>测试页面</title>
    <link rel="stylesheet" href="./usualEffects/css/myDatePicker.css">
</head>

<body>
    <input type="text" id="myDatePicker">
    <!--
    <div class="myDatePicker">
        <div class="title">
            <span class="l"><</span>
            <span class="c"><span class="year">2016</span>年<span class="month">5</span>月</span>
            <span class="r">></span>
        </div>
        <table>
            <thead>
                <tr>
                    <th>周一</th>
                    <th>周二</th>
                    <th>周三</th>
                    <th>周四</th>
                    <th>周五</th>
                    <th class="red">周六</th>
                    <th class="red">周日</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>1</td>
                    <td>1</td>
                    <td>1</td>
                    <td>1</td>
                    <td>1</td>
                    <td>1</td>
                </tr>
            </tbody>
        </table>
    </div>
-->
    <script src="./commonJs/tool.js"></script>
    <script src="./commonJs/base.js"></script>
    <script src="./commonJs/base_datePicker.js"></script>
    <script>
    $(\'#myDatePicker\').datePicker();
    </script>
</body>

</html>
自定义日历控件使用方法示例