码迷,mamicode.com
首页 > 编程语言 > 详细

Javascript——date日历控件

时间:2015-02-13 16:05:25      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
*功能没全,还需要自己修改
<!DOCTYPE html>
<html>
<head>
    <meta content="width =device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
    <meta content="yes" name="apple-mobile-web-app-capable" />
    <meta content="black" name="apple-mobile-web-app-status-bar-style" />
    <meta content="telephone =no" name="format-detection" />
    <title>日期控件</title>
    <link href="/Css/Date.css" rel="stylesheet" />
</head>
<body>
    <input id="txttime" value="2015-5-31" style="height:25px;border:1px solid #e2e2e2;margin:50px;width:250px;line-height:25px;font:15px/1.5 ‘Microsoft YaHei‘;padding:5px 0px;text-align:center;color:#ff0000" />
    <div class="fc-date-box" id="trtarget" style="display:none;">
        <div class="fc-box" id="fc-box">
            <a class="fc-ico fc-ico-l" id="fc-ico-l"><i></i></a>
            <input class="fc-input input-YY" id="input-YY" value="" readonly="readonly" />
            <span>年</span>
            <input class="fc-input input-MM" id="input-MM" value="" readonly="readonly" />
            <span>月</span>
            <a class="fc-ico fc-ico-r" id="fc-ico-r"><i></i></a>
            <div class="fc-YY-list-box"></div>
            <div class="fc-MM-list-box"></div>
        </div>
        <div class="f-d-list-box">
            <table id="fc-date-table">
                <thead><tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr></thead>
            </table>
        </div>
        <div class="f-d-week-keepout"></div>
        <div class="f-d-week-error">
            <p class="f-d-w-e-tit">信息</p>
            <div class="f-d-w-e-content">
                <p><span class="span1"></span><span id="f-d-w-e-span">格式不正确</span></p>
                <a href="#" id="btn-ok">确 定</a>
            </div>
        </div>
    </div>
    <span id="el"></span>
    <script src="/Scripts/Date.js"></script>
</body>
</html>

  

/*日历控件
暂时只支持input
*/
!(function (win) {
    var options = {
        inputdom: document.getElementById(‘txttime‘),//操作input
        event: ‘focus‘,//触发方式
        format: ‘YYYY-MM-dd‘,//格式化格式
        min: ‘1900-1-1‘,
        max: ‘2099-12-31‘,
        fn: null
    };
    //扩展options
    options.extend = function (options) {
        for (var o in options) {
            //console.log(options.hasOwnProperty(o));
            if (options.hasOwnProperty(o)) {
                this[o] = options[o];
            }
        }
    }

    //公共方法
    var Common = {
        each: function (arrydom, fn) {
            var len = arrydom.length;
            for (var i = 0; i < len; i++) {
                if (typeof fn == ‘function‘) {
                    fn.call(arrydom[i]);
                }
            }
        },
        //绑定事件
        on: function (dom, even, fn) {
            dom.attachEvent ? dom.attachEvent(‘on‘ + even, function (e) {
                e = e || window.event;
                (e.stopPropagation && e.stopPropagation());
                if (e.cancelBubble) e.cancelBubble = false;
                fn.call(dom, e);
            }) : dom.addEventListener(even, function (e) {
                e = e || window.event;
                (e.stopPropagation && e.stopPropagation());
                if (e.cancelBubble) e.cancelBubble = false;
                fn.call(dom, e);
            }, false);
        },
        on2: function (dom, even, fn) {
            dom.attachEvent ? dom.attachEvent(‘on‘ + even, function (e) {
                e = e || window.event;
                fn.call(dom, e);
            }) : dom.addEventListener(even, function (e) {
                e = e || window.event;
                fn.call(dom, e);
            }, false);
        },
        //获得属性
        attr: function (dom, attr, val) {
            var str = ‘‘, s;
            if (val) {
                dom.setAttribute(this.trim(attr), val);
                attr.toLowerCase() == ‘class‘ && (dom.className = val);
                attr.toLowerCase() == ‘style‘ && (dom.style.cssText = val);
            }
            else {
                s = dom.getAttribute(attr);
                str = s;
                attr.toLowerCase() == ‘class‘ && (str = dom.className);
                attr.toLowerCase() == ‘style‘ && (str = dom.style.cssText);
                return this.trim(str);
            }
        },
        //删除属性
        removeattr: function (dom, attr) {
            dom.removeAttribute(attr);
        },
        //判断是否存在class
        hasClass: function (dom, str) {
            return new RegExp(‘\\b‘ + str + ‘\\b‘).test(dom.className);
        },
        //添加class
        addClass: function (dom, cls) {
            this.hasClass(dom, cls) || (dom.className += ‘ ‘ + cls);
            dom.className = this.trim(dom.className);
        },
        //删除class
        removeClass: function (dom, cls) {
            var c = this.trim(cls), reg = new RegExp(‘\\b‘ + c + ‘\\b‘);

            if (this.hasClass(dom, c)) {
                dom.className = this.trim(dom.className.replace(reg, ‘‘));
            }
        },
        //去除前后空格
        trim: function (s) {//去除多于空格
            s = s.toString() || ‘‘;
            return s.replace(/^\s*|\s*$/g, ‘‘);
        },
        mouseenter: function (dom, fn) {
            var f = true;
            if (dom.attachEvent) {
                this.on(dom, "mouseenter", fn);
            }
            else {
                this.on(dom, "mouseover", function (e) {
                    if (f) {
                        var mya = (e.srcElement ? e.srcElement : e.target);
                        var parent = e.relatedTarget || e.fromElement;
                        while (parent && parent != dom) {
                            try { parent = parent.parentNode; }
                            catch (e) { break; }
                        }
                        if (parent != dom) {
                            f = (function () { fn.call(dom, e); return true; })();
                        }
                    }
                });
            }

        },
        mouseleave: function (dom, fn) {
            if (dom.attachEvent) {
                this.on(dom, "mouseleave", fn);
            }
            else {
                this.on(dom, "mouseout", function (e) {
                    var mya = (e.srcElement ? e.srcElement : e.target);
                    var parent = e.relatedTarget || e.toElement;
                    while (parent && parent != dom) {
                        try { parent = parent.parentNode; }
                        catch (e) { break; }
                    }
                    if (parent != this) { fn.call(dom, e); }
                });
            }
        }
    };

    var Dates = {
        //补位
        digit: function (m) {
            return +m < 10 ? ‘0‘ + m : m;
        },
        //日期格式化可date可是数组也可以是字符串
        parse: function (date, format) {
            var _index = 0;
            if (typeof date == ‘string‘) date = this.toarry(date);
            if (date == null) return ‘‘;
            //console.log(date);
            format = format || ‘YYYY-MM-dd HH:mm:ss‘;
            return format.replace(/YYYY|MM|dd|HH|mm|ss/g, function (str, index, s) {
                return Dates.digit(date[_index++]);
            });
        },
        //获指定日期
        now: function (timestamp, format) {
            var _parsestr, _date = new Date((timestamp | 0) ? function () {
                var _datenow = new Date();
                if (timestamp >= 86400000) {
                    return timestamp + _datenow.getHours() * 3600000 + _datenow.getMinutes() * 60000 + _datenow.getSeconds() * 1000;
                }
                return 86400000 * timestamp + _datenow.getTime();
            }(timestamp) : new Date);
            _parsestr = [_date.getFullYear(), (_date.getMonth() + 1), _date.getDate(), _date.getHours(), _date.getMinutes(), _date.getSeconds()];
            return {
                //返回字符串
                Totime: this.parse(_parsestr, format),
                //返回数组
                Toarry: _parsestr
            };
        },
        //日期序列化
        toarry: function (timestr) {
            var aryy = this.Isdate(timestr, true);//日期正确返回日期数组[YYYY,MM,dd,HH,mm,ss]
            if (!aryy) return null;
            return aryy;
        },
        //验证日期,设置第二个参数可以返回现在日期数组[YYYY,MM,dd,HH,mm,ss]
        Isdate: function (datestr, isreturn) {
            var _DateReg = /^((\d{4})(-|\/)(\d{1,2})\3(\d{1,2}))( (\d{1,2}):(\d{1,2}):(\d{1,2}))?$/,//2015-1-43 3:3:44||2015-1-43 99:99:99
                _Date,
                _result,
                _YYYY, _MM, _dd, _HH = 0, _mm = 0, _ss = 0, _istrue = false;
            if (_DateReg.test(datestr)) {//验证格式正确
                _result = _DateReg.exec(datestr);//datestr.match(reg);
                //console.log(_result);
                if (_result == null) return false;
                _YYYY = _result[2];
                _MM = +_result[4] - 1;
                _dd = _result[5];
                if (_result[6] != undefined && _result[6] != ‘‘) {
                    _HH = _result[7];
                    _mm = _result[8];
                    _ss = _result[9];
                }
                _Date = new Date(_YYYY, _MM, _dd, _HH, _mm, _ss);
                _istrue = (_Date.getFullYear() == _YYYY && _Date.getMonth() == _MM && _Date.getDate() == _dd && _Date.getHours() == _HH && _Date.getMinutes() == _mm && _Date.getSeconds() == _ss);
                return (_istrue && (isreturn && [_YYYY, (_MM + 1), _dd, _HH, _mm, _ss])) || _istrue;
            }
            else {
                return false;
            }
        },
        //润年判断
        LeapYear: function (year) {
            if ((year % 100 == 0 && year % 400 == 0) || year % 4 == 0) return true;
            return false;
        }
    };

    var domtrtarget = document.getElementById(‘trtarget‘),
        domfc = document.getElementById(‘fc-date-table‘),//容器
        domYYYY = document.getElementById(‘input-YY‘),
        domMM = document.getElementById(‘input-MM‘),
        domfc_l = document.getElementById(‘fc-ico-l‘),//前一月
        domfc_r = document.getElementById(‘fc-ico-r‘),//后一月
        td_this_class = ‘fc-foucs-this‘,//当前td样式
        td_no_class = ‘no-fc‘;//notd样式

    var timeout1 = false;//延迟input blur发生
    var _arrym_d = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var _nowarry = Dates.now().Toarry;//日期数组
    var _nowday = new Date(_nowarry[0] + ‘/‘ + _nowarry[1] + ‘/1‘).getDay();//星期数
    var _arrydom = [];//td-dom 页面数组
    var Fcdate = {
        //数据写入内存防止用户篡改
        Options: {
            thisYYYY: null,//当前年份
            thisMM: null,//当前月份
            thisDD: null,//当前日期
            thisHH: null,
            thismm: null,
            thisss: null,
            maxYYYY: null,
            minYYYY: null
        },
        //为目标dom创建focus事件
        ondom: function () {
            var _cur = this,
                _focusdom = options.inputdom;
            _cur.Init();
            Common.on(_focusdom, ‘focus‘, function () {
                timeout1 = true;
                //console.log(this.offsetHeight + "," + this.offsetTop + ‘,‘ + this.offsetTop);
                domtrtarget.style.top = this.offsetHeight + this.offsetTop + ‘px‘;
                domtrtarget.style.left = this.offsetLeft + ‘px‘;
                domtrtarget.style.display = ‘block‘;
            });
            Common.on2(document, ‘click‘, function (e) {
                var _target = e.target || e.srcElement
                if (_target === _focusdom) {
                    //console.log(_focusdom);
                    return;
                }
                if (timeout1) {
                    domtrtarget.style.display = ‘none‘;
                    timeout1 = false;
                }
                //console.log(timeout1);
            });
        },
        //主函数
        Init: function (opt) {
            var _thisnewarry;
            if (opt) {
                options.extend(opt);
            }
            if (Common.trim(options.inputdom.value) != ‘‘) {
                _thisnewarry = Dates.toarry(options.inputdom.value);
                _nowarry = _thisnewarry || _nowarry;
                _nowday = (_thisnewarry && (this.GetFirstDay(_thisnewarry[0], _thisnewarry[1]))) || _nowday;
            }
            this.Options.thisDD = _nowarry[2];
            this.LeapYear(_nowarry[0]);
            this.SetyyyyMM(3, _nowarry);
            this.CeartTbody();
            this.BindFn();
            _thisnewarry = null;
        },
        //创建table
        CeartTbody: function () {
            var _cur = this;
            //console.log(domfc.getElementsByTagName(‘tbody‘).length);
            if (domfc.getElementsByTagName(‘tbody‘).length > 0) {
                for (var i = 0, j = domfc.getElementsByTagName(‘tbody‘).length; i < j; i++) {
                    domfc.removeChild(domfc.getElementsByTagName(‘tbody‘)[i]);
                }
            }
            var _tbody = document.createElement(‘tbody‘), _tr = null;
            for (var i = 0; i < 42; i++) {
                if (i == 0 || i == 7 || i == 14 || i == 21 || i == 28 || i == 35) {
                    _tr = document.createElement(‘tr‘);
                    _tbody.appendChild(_tr);
                }
                var _td = document.createElement(‘td‘);
                if (i >= _nowday && i < (_arrym_d[_nowarry[1] - 1] + _nowday)) {
                    var _day = i - _nowday + 1;
                    _td.innerHTML = _day;
                    Common.attr(_td, ‘data-y‘, _nowarry[0]);
                    Common.attr(_td, ‘data-m‘, _nowarry[1]);
                    Common.attr(_td, ‘data-d‘, _day);
                    this.Isday(_td, _day);
                    _arrydom.push(_td);
                }
                else {
                    Common.addClass(_td, td_no_class);
                }
                _tr.appendChild(_td);
            }
            domfc.appendChild(_tbody);
            //td点选事件
            Common.on2(_tbody, ‘click‘, function (e) {
                var _target = e.target || e.srcElement, _nowtime = new Date(), _newtime;
                if (_target.tagName.toLowerCase() === ‘td‘ && _target.nodeType == 1 && !Common.hasClass(_target, td_no_class)) {
                    (e.stopPropagation && e.stopPropagation());
                    if (e.cancelBubble) e.cancelBubble = false;
                    _newtime = Dates.parse(Common.attr(_target, ‘data-y‘) + ‘/‘ + Common.attr(_target, ‘data-m‘) + ‘/‘ + Common.attr(_target, ‘data-d‘) + ‘ ‘ + _nowtime.getHours() + ‘:‘ + _nowtime.getMinutes() + ‘:‘ + _nowtime.getSeconds(), options.format);
                    if (!_newtime) { alert(‘注意,内里被篡改!‘); return; }
                    if (Common.hasClass(_target, td_this_class)) {
                        return false;
                    }
                    Common.each(_arrydom, function () {
                        Common.removeClass(this, td_this_class);
                    });
                    Common.addClass(_target, td_this_class);
                    //console.log(_newtime);
                    _cur.Options.thisDD = Common.attr(_target, ‘data-d‘);
                    options.inputdom.value = _newtime;
                    domtrtarget.style.display = ‘none‘;
                    //console.log(this);
                }
            });
        },
        //判断当前选中日期
        Isday: function (td, day) {
            if (this.Options.thisDD == day) {
                Common.addClass(td, td_this_class);
            }
        },
        //写入input
        SetInput: function () { },
        //绑定事件
        BindFn: function () {
            var _cur = this;
            //前一月事件
            Common.on(domfc_l, ‘click‘, function (e) {
                _cur.SetyyyyMM(1);
                _cur.Change();
            });
            //下一月事件
            Common.on(domfc_r, ‘click‘, function (e) {
                _cur.SetyyyyMM(2);
                _cur.Change();
            });
        },
        //日期改变
        Change: function () {
            _nowday = this.GetFirstDay(domYYYY.value, domMM.value);
            _nowarry = [domYYYY.value.toString(), domMM.value.toString()];
            this.LeapYear(_nowarry[0]);
            this.CeartTbody();
        },
        //润年判断
        LeapYear: function (year) {
            if (Dates.LeapYear(year)) _arrym_d[1] = 29;
            _arrym_d[1] = 28;
        },
        //设置当前年月
        SetyyyyMM: function (type, arry) {
            var yyyy = +domYYYY.value, MM = +domMM.value;
            switch (type) {
                case 1:
                    if (MM == 1) {
                        domYYYY.value = yyyy - 1;
                        domMM.value = 12;
                    }
                    else {
                        domMM.value = Dates.digit(MM - 1);
                    }
                    break;
                case 2:
                    if (MM == 12) {
                        domYYYY.value = yyyy + 1;
                        domMM.value = Dates.digit(1);
                    }
                    else {
                        domMM.value = Dates.digit(MM + 1);
                    }
                    break;
                case 3:
                    domYYYY.value = arry[0];
                    domMM.value = Dates.digit(+arry[1]);
                    break;
            }
        },
        //每月1日的星期数
        GetFirstDay: function (year, MM) {
            return new Date(year + ‘/‘ + MM + ‘/1‘).getDay();
        }
    };
    win.Fcdates = function () { Fcdate.ondom.call(Fcdate); };
    Fcdates();
})(window);

  

Javascript——date日历控件

标签:

原文地址:http://www.cnblogs.com/yc-code/p/4290305.html

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