金沙棋牌官方平台

当前位置:金沙棋牌 > 金沙棋牌官方平台 > Firefox的日历控件,编写一个符合国情的日期插件

Firefox的日历控件,编写一个符合国情的日期插件

来源:http://www.logblo.com 作者:金沙棋牌 时间:2019-11-29 12:42

手把手教你打造一款别致的时间线插件

2016/06/17 · JavaScript · 1 评论 · 插件

原文出处: 郑武江(@OAuth_v2)   

金沙棋牌官方平台 1

首先呢,我要感谢一下和我配合的设计师同学,给了我一份如此漂亮的时间线设计稿。拿到设计稿后,我们首先要做的是去分析整个作品的结构,及设计意图。当然这些工作我们可以提前完成,在设计师设计的时候进行充分沟通,而当我们动手去实现的时候就更为得心应手了。开始之前,我们还是先看看最终的交互效果:

金沙棋牌官方平台 2

第一步,分析控件结构,说多了反而容易引起误导,直接看图吧,直观明了:

金沙棋牌官方平台 3

接下来,我来说说我为什么要这么去划分。简单的说,在我看来分析一个控件的结构,其实就是尝试去发现一些规律性的东西。如上图,在月份栏很明显是在每月第一日的位置上方显示当月标签,因此第一行自然可以独立成一个在特定位置显示月份信息的独立区域。而第二行更明显,将时间线上的每一天从左往右挨个儿显示就行了,很显然这一行上只会出现具体天的数据,所以我也将它独立成一个区域。再往下,我们先看最下面的刻度区域,这里存在一定的迷惑性,由于每月第一天的那条线高度刚好填充满,而两个月的第一天刚好将整条刻度划分成一个一个的小区间,但事实上,我觉得它们其实就是一条横向连通的刻度线,所以应该整个一行是一个整体。最后再来说说灰色、蓝色重叠的那条区域,我们可以把蓝色区域包含在灰色区域之中,也可以分成两个同级的区域重叠在一起。但这里需要注意一点:蓝色区域表明的是一个时间区间,它的水平位置和宽度是随时可变的,所以,考虑到后面定位的方便,未知的需求变化,我更倾向分成两个独立区域重叠起来。

第二步,细化每个区域中的共同点,不同点。月份栏,没有问题,就是在每月第一天的位置显示月份标签,唯一不同的是每月第一天的横坐标(left)。日期栏基本与月份栏情况一致,多一点不同在于实现过程中考虑突出显示【今天】。灰色线很简单,从左到右一拉到底,蓝色线很显然是在选中某个事件标签的时候才会出现,所以期初也不用考虑。最后还是刻度栏相对复杂一点,水平位置上的差异不再多说,每月第一天需要追加高刻度样式,而且为了方便后面与事件标签关联,我们需要在生成刻度的时候,在每个刻度上存上对应的日期。大致就是这样,下面就可以着手编码了。

第三步,搭框架。就好像画素描一样,先勾勒出整个作品的骨架,再慢慢细化。

金沙棋牌官方平台 4

代码很简单,先创建一个时间线全局容器,再往里面写入第一步和第二步中我们分析出来的几个独立区块,最后想整个时间线放入页面中准备好的节点(wrap)中。

第四步,写静态数据,细节优化。根据前面的分析,各个部分的容器都已经准备就绪,接着就该将各部分应该呈现的内容写入到对应的位置中去了,这一步代码会稍微多些。而且根据自己的需求,可能在某些判断逻辑上会略显不同,先看看我的示例代码吧:

JavaScript

var Utils = { // 格式化数字,小于10补前置0 prefixZero: function(num) { return num < 10 ? '0' + num : num; } }; function createTimeline(from, to) { var Timeline, f = typeof from === 'string' ? new Date(from.replace(/-/g, '/')) : from, t = typeof to === 'string' ? new Date(to.replace(/-/g, '/')) : to, timestamp = t - f, day = 24 * 60 * 60 * 1000, today = new Date(), miliStart = f.getTime(), dayCount = Math.floor(timestamp / day) + 1, // 计算时间轴上显示的总天数 offLeft = 12, // 初始日期左边距 offRight = 12, // 结束日期右边距 offDay = 20, // 日与日之间的间距 lineLength = dayCount * offDay + offLeft + offRight; // 计算时间轴的长度 var line = $('<div class="J_TimeLine timeline-slider"></div>'), monthLabel, dayLabel, dayDiff, scaleLabel; line.css({width: lineLength, height: 134}); line.html('<div class="J_MonthLabel month-label"></div>' + '<div class="J_DayLabel day-label"></div>' + '<div class="J_ScaleLine scale-line"></div>' + '<div class="J_DayDiff day-diff"></div>' + '<div class="J_ScaleLabel scale-label"></div>'); monthLabel = line.find('.J_MonthLabel'); dayLabel = line.find('.J_DayLabel'); dayDiff = line.find('.J_DayDiff'); scaleLabel = line.find('.J_ScaleLabel'); for (var i = 0; i < dayCount; i++) { var d = new Date(miliStart + i * day), left = i * offDay + offLeft, monthObj, dayObj, scaleObj; dayObj = $('<span class="J_Day day"></span>'); dayObj.css('left', left - 9); dayObj.html(d.getDate()); // 如果【今天】在时间轴范围内,则强调显示 if (d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth() && d.getDate() === today.getDate()) { dayObj.addClass('today'); } scaleObj = $('<span class="J_Scale scale"></span>'); scaleObj.css('left', left); scaleObj.attr('data-date', d.getFullYear() + '/' + Utils.prefixZero(d.getMonth() + 1) + '/' + Utils.prefixZero(d.getDate())); // 在每月第一天的上方显示月份信息 if (d.getDate() === 1) { scaleObj.addClass('first-day'); monthObj = $('<span class="J_Month month"></span>'); monthObj.css('left', left); monthObj.html(d.getFullYear() + '/' + Utils.prefixZero(d.getMonth() + 1)); monthLabel.append(monthObj); } dayLabel.append(dayObj); scaleLabel.append(scaleObj); } tw.html('').append(line); Timeline = { slider: line, monthLabel: monthLabel, dayLabel: dayLabel, dayDiff: dayDiff, scaleLabel: scaleLabel }; return Timeline; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
var Utils = {
    // 格式化数字,小于10补前置0
    prefixZero: function(num) {
        return num < 10 ? '0' + num : num;
    }
};
 
function createTimeline(from, to) {
    var Timeline,
        f = typeof from === 'string' ? new Date(from.replace(/-/g, '/')) : from,
        t = typeof to === 'string' ? new Date(to.replace(/-/g, '/')) : to,
        timestamp = t - f,
        day = 24 * 60 * 60 * 1000,
        today = new Date(),
        miliStart = f.getTime(),
        dayCount = Math.floor(timestamp / day) + 1, // 计算时间轴上显示的总天数
        offLeft = 12, // 初始日期左边距
        offRight = 12, // 结束日期右边距
        offDay = 20, // 日与日之间的间距
        lineLength = dayCount * offDay + offLeft + offRight; // 计算时间轴的长度
 
    var line = $('<div class="J_TimeLine timeline-slider"></div>'),
        monthLabel, dayLabel, dayDiff, scaleLabel;
 
    line.css({width: lineLength, height: 134});
    line.html('<div class="J_MonthLabel month-label"></div>'
        + '<div class="J_DayLabel day-label"></div>'
        + '<div class="J_ScaleLine scale-line"></div>'
        + '<div class="J_DayDiff day-diff"></div>'
        + '<div class="J_ScaleLabel scale-label"></div>');
    monthLabel = line.find('.J_MonthLabel');
    dayLabel = line.find('.J_DayLabel');
    dayDiff = line.find('.J_DayDiff');
    scaleLabel = line.find('.J_ScaleLabel');
 
    for (var i = 0; i < dayCount; i++) {
        var d = new Date(miliStart + i * day),
            left = i * offDay + offLeft,
            monthObj, dayObj, scaleObj;
 
        dayObj = $('<span class="J_Day day"></span>');
        dayObj.css('left', left - 9);
        dayObj.html(d.getDate());
        // 如果【今天】在时间轴范围内,则强调显示
        if (d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth() && d.getDate() === today.getDate()) {
            dayObj.addClass('today');
        }
 
        scaleObj = $('<span class="J_Scale scale"></span>');
        scaleObj.css('left', left);
        scaleObj.attr('data-date', d.getFullYear() + '/' + Utils.prefixZero(d.getMonth() + 1) + '/' + Utils.prefixZero(d.getDate()));
        // 在每月第一天的上方显示月份信息
        if (d.getDate() === 1) {
            scaleObj.addClass('first-day');
            monthObj = $('<span class="J_Month month"></span>');
            monthObj.css('left', left);
            monthObj.html(d.getFullYear() + '/' + Utils.prefixZero(d.getMonth() + 1));
            monthLabel.append(monthObj);
        }
 
        dayLabel.append(dayObj);
        scaleLabel.append(scaleObj);
    }
 
    tw.html('').append(line);
    Timeline = {
        slider: line,
        monthLabel: monthLabel,
        dayLabel: dayLabel,
        dayDiff: dayDiff,
        scaleLabel: scaleLabel
    };
    return Timeline;
}

第五步,整合服务端数据。经过以上代码的处理,我们只需简单调用createTimeline(fromDate, toDate)就可以在页面上得到一条静态的时间轴,看起来像:

金沙棋牌官方平台 5

而我们在前面的工作中已经对每一个刻度标记了对应日期,现在只需从服务端将哪些日期对于有相应的特殊事件获取回来并和时间轴上的刻度进行关联,我们的工作就差不多了。这里我们就不去模拟服务端的请求了,我们直接构造一份静态数据来制作演示效果。我们假设服务端返回的数据结构如下:

JavaScript

var serverData = { snapshotTimes: [{ date: '2016/06/01', content: 'JD618大促启动' }, { date: '2016/06/18', content: '京东618大促进行时' }, { date: '2016/09/15', content: '2016年中秋节放假' }] };

1
2
3
4
5
6
7
8
9
10
11
12
var serverData = {
    snapshotTimes: [{
        date: '2016/06/01',
        content: 'JD618大促启动'
    }, {
        date: '2016/06/18',
        content: '京东618大促进行时'
    }, {
        date: '2016/09/15',
        content: '2016年中秋节放假'
    }]
};

我们可以使用下面的代码,将数据绑定到时间轴刻度上:

JavaScript

var data = serverData.snapshotTimes, tLen = data.length, tempDate, tlBegin, tlEnd; tlBegin = data[0].date; tempDate = new Date(data[tLen

  • 1].date); // 时间轴最后预留三个月空时段,保证时间轴的视觉效果美观 if (tempDate.getMonth() > 8) { tlEnd = (tempDate.getFullYear() + 1) + '/0' + ((tempDate.getMonth() + 3) % 11) + '/' + Utils.prefixZero(tempDate.getDate()); } else { tlEnd = tempDate.getFullYear() + '/' + Utils.prefixZero(tempDate.getMonth() + 4)
  • '/' + Utils.prefixZero(tempDate.getDate()); } // 根据服务端数据的起始日期,初始化时间轴 TL = createTimeline(tlBegin, tlEnd); // 根据日期,将事件触发器绑到对应刻度上 $.each(data, function(idx, d){ var sc = TL.scaleLabel.find('.J_Scale[data-date="' + d.date + '"]'), sct = sc.attr('data-date'), scArr = sct.split('/'); sc.addClass('has-snap').html('<a href="#' + sct + '" class="J_SnapshotLink snapshot-link">' + scArr[1] + '月' + scArr[2] + '</a>'); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var data = serverData.snapshotTimes,
    tLen = data.length, tempDate,
    tlBegin, tlEnd;
tlBegin = data[0].date;
tempDate = new Date(data[tLen - 1].date);
// 时间轴最后预留三个月空时段,保证时间轴的视觉效果美观
if (tempDate.getMonth() > 8) {
    tlEnd = (tempDate.getFullYear() + 1) + '/0' + ((tempDate.getMonth() + 3) % 11) + '/' + Utils.prefixZero(tempDate.getDate());
} else {
    tlEnd = tempDate.getFullYear() + '/' + Utils.prefixZero(tempDate.getMonth() + 4) + '/' + Utils.prefixZero(tempDate.getDate());
}
// 根据服务端数据的起始日期,初始化时间轴
TL = createTimeline(tlBegin, tlEnd);
// 根据日期,将事件触发器绑到对应刻度上
$.each(data, function(idx, d){
    var sc = TL.scaleLabel.find('.J_Scale[data-date="' + d.date + '"]'),
        sct = sc.attr('data-date'),
        scArr = sct.split('/');
    sc.addClass('has-snap').html('<a href="#' + sct + '" class="J_SnapshotLink snapshot-link">' + scArr[1] + '月' + scArr[2] + '</a>');
});

现在,我们的时间轴看起来更丰满了:

金沙棋牌官方平台 6

第六步,绑定事件,实现点击对应标签选中对应区间段及其他操作。同样,有了如今的界面及元素,我们就该考虑如何实现点击某个标签选中该标签到下一个标签这个区间了。其实,在我们绑定服务端数据的时候,我们已经做了一些准备,在第五步的代码中我们不难发现,我给每一个标签对应的刻度元素添加了一个has-snap的标记class。那么,接下来就简单多了,选中区间无非就是当前被点击标签对应的刻度到下一个含有has-snap标记的刻度之间的距离了。因此,我又设计了一个根据日期字符串对象实现选中区间的方法,如下:

JavaScript

function selectByDate(dateStr) { var ele = TL.scaleLabel.find('.J_Scale[data-date="' + dateStr.replace(/-/g, '/')

  • '"]'), nextEle = ele.nextAll('.has-snap').eq(0), nLast, nl, nw, today = new Date(), lastDate; if (!ele.length) { return; } nl = parseFloat(ele.css('left')); if (nextEle.length) { // 如果存在下一个有has-snap标记的元素 nLast = nextEle; lastDate = new Date(nLast.attr('data-date')); } else { // 如果已是最后一个有has-snap标记的元素 nLast = TL.scaleLabel.find('.J_Scale').last(); lastDate = new Date(nLast.attr('data-date')); // 如果最后一个刻度日期大于今天,则结束刻度设为今天,否则使用最后刻度 if (lastDate > today) { lastDate = today; nLast = TL.scaleLabel.find('.J_Scale[data-date="' + (today.getFullYear() + '/'
  • Utils.prefixZero(today.getMonth() + 1) + '/' + Utils.prefixZero(today.getDate())) + '"]'); } } // 这里是对选中某项后做一些其他业务,与本文关系不太大 if (!nextEle.length && lastDate !== today) { selDays.html(Math.floor((today - new Date(ele.attr('data-date'))) / (24 * 60 * 60 * 1000))); selRange.html(ele.attr('data-date').replace(///g, '-') + ' ~ ' + '今天'); nw = parseFloat(nLast.css('left')) - parseFloat(ele.css('left')) + 32; } else { selDays.html(Math.floor((new Date(nLast.attr('data-date')) - new Date(ele.attr('data-date'))) / (24 * 60 * 60 * 1000))); selRange.html(ele.attr('data-date').replace(///g, '-') + ' ~ ' + nLast.attr('data-date').replace(///g, '-')); nw = parseFloat(nLast.css('left')) - parseFloat(ele.css('left')); } viewFrame.attr('src', '/decorate/getSnapshotInfoByAppAndTime.html?appId=' + appId + '&snapshotTime=' + ele.attr('data-date').replace(///g, '-')); TL.scaleLabel.find('.active').removeClass('active'); ele.find('.J_SnapshotLink').addClass('active'); TL.dayDiff.css({left: nl, width: 0}); TL.dayDiff.animate({width: nw}, 300); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function selectByDate(dateStr) {
    var ele = TL.scaleLabel.find('.J_Scale[data-date="' + dateStr.replace(/-/g, '/') + '"]'),
        nextEle = ele.nextAll('.has-snap').eq(0),
        nLast, nl, nw,
        today = new Date(),
        lastDate;
    if (!ele.length) {
        return;
    }
    nl = parseFloat(ele.css('left'));
    if (nextEle.length) { // 如果存在下一个有has-snap标记的元素
        nLast = nextEle;
        lastDate = new Date(nLast.attr('data-date'));
    } else { // 如果已是最后一个有has-snap标记的元素
        nLast = TL.scaleLabel.find('.J_Scale').last();
        lastDate = new Date(nLast.attr('data-date'));
        // 如果最后一个刻度日期大于今天,则结束刻度设为今天,否则使用最后刻度
        if (lastDate > today) {
            lastDate = today;
            nLast = TL.scaleLabel.find('.J_Scale[data-date="' + (today.getFullYear() + '/' + Utils.prefixZero(today.getMonth() + 1) + '/' + Utils.prefixZero(today.getDate())) + '"]');
        }
    }
    // 这里是对选中某项后做一些其他业务,与本文关系不太大
    if (!nextEle.length && lastDate !== today) {
        selDays.html(Math.floor((today - new Date(ele.attr('data-date'))) / (24 * 60 * 60 * 1000)));
        selRange.html(ele.attr('data-date').replace(///g, '-') + ' ~ ' + '今天');
        nw = parseFloat(nLast.css('left')) - parseFloat(ele.css('left')) + 32;
    } else {
        selDays.html(Math.floor((new Date(nLast.attr('data-date')) - new Date(ele.attr('data-date'))) / (24 * 60 * 60 * 1000)));
        selRange.html(ele.attr('data-date').replace(///g, '-') + ' ~ ' + nLast.attr('data-date').replace(///g, '-'));
        nw = parseFloat(nLast.css('left')) - parseFloat(ele.css('left'));
    }
    viewFrame.attr('src', '/decorate/getSnapshotInfoByAppAndTime.html?appId=' + appId + '&snapshotTime=' + ele.attr('data-date').replace(///g, '-'));
    TL.scaleLabel.find('.active').removeClass('active');
    ele.find('.J_SnapshotLink').addClass('active');
    TL.dayDiff.css({left: nl, width: 0});
    TL.dayDiff.animate({width: nw}, 300);
}

接着,就该是对每一个标签绑定事件,让每个标签被点击的时候实现选中等效果了。这里顺便将时间轴的拖拽及回弹功能也一并提供了:

JavaScript

tw.delegate('.J_TimeLine', 'mousedown', function(ev){ // 拖拽及回弹 var originX = ev.clientX, moveX = originX, delta = 0, originLeft = parseFloat(TL.slider.css('left')); if (TL.slider.width() < tw.width()) { return true; } TL.slider.data('moved', false); doc.bind('mousemove', function(ev){ moveX = ev.clientX; delta = moveX - originX; if (Math.abs(delta) > 10) { TL.slider.css('left', originLeft

  • delta + 'px'); } }); doc.bind('mouseup', function(ev){ doc.unbind('mousemove'); doc.unbind('mouseup'); if (Math.abs(delta) <= 10) { TL.slider.data('moved', false); } else { TL.slider.data('moved', true); } var tLeft = parseFloat(TL.slider.css('left')), tWidth = tw.width(); if (tLeft > 0) { TL.slider.animate({'left': 0}, 300, function(){}); } else if (Math.abs(tLeft) > TL.slider.width() - tWidth) { TL.slider.animate({'left': '-' + (TL.slider.width() - tWidth) + 'px'}, 300, function(){}); } }); }).delegate('.J_SnapshotLink', 'click', function(ev){ // 标签点击选中事件 if (TL.slider.data('moved')) { return false; } var _this = $(this), hrefArr = _this.attr('href').split('#'); selectByDate(hrefArr[1]); ev.preventDefault(); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
tw.delegate('.J_TimeLine', 'mousedown', function(ev){ // 拖拽及回弹
    var originX = ev.clientX,
        moveX = originX,
        delta = 0,
        originLeft = parseFloat(TL.slider.css('left'));
    if (TL.slider.width() < tw.width()) {
        return true;
    }
    TL.slider.data('moved', false);
    doc.bind('mousemove', function(ev){
        moveX = ev.clientX;
        delta = moveX - originX;
        if (Math.abs(delta) > 10) {
            TL.slider.css('left', originLeft + delta + 'px');
        }
    });
    doc.bind('mouseup', function(ev){
        doc.unbind('mousemove');
        doc.unbind('mouseup');
 
        if (Math.abs(delta) <= 10) {
            TL.slider.data('moved', false);
        } else {
            TL.slider.data('moved', true);
        }
 
        var tLeft = parseFloat(TL.slider.css('left')),
            tWidth = tw.width();
        if (tLeft > 0) {
            TL.slider.animate({'left': 0}, 300, function(){});
        } else if (Math.abs(tLeft) > TL.slider.width() - tWidth) {
            TL.slider.animate({'left': '-' + (TL.slider.width() - tWidth) + 'px'}, 300, function(){});
        }
    });
}).delegate('.J_SnapshotLink', 'click', function(ev){ // 标签点击选中事件
    if (TL.slider.data('moved')) {
        return false;
    }
    var _this = $(this),
        hrefArr = _this.attr('href').split('#');
    selectByDate(hrefArr[1]);
    ev.preventDefault();
});

好了,到这里我们的时间轴功能就全部完成了。只需要对上面的方法进行包装,我们就可以得到一个功能比较完善的时间轴插件了。实例演示:一个干净清爽的时间线实例

1 赞 5 收藏 1 评论

金沙棋牌官方平台 7

<html>
<head>
<title>日期输入框演示-queyang.com</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">script
<style>
body{font-size:12px;font-family:Verdana,Arial,"宋体";}
a:link {color:#464646;text-decoration:none;}
a:visited {color:#464646;text-decoration:none;}iframe
a:hover{color:#ed145b;text-decoration:underline;}
a:active{color:#ed145b;text-decoration:underline;}
td{font-size:12px}
/*想要改输入日历控件的样子就改下面的CSS样式就可以了*/
/*Date*/
.header {font: 12px Arial, Tahoma !important;font-weight: bold !important;font: 11px Arial, Tahoma;font-weight: bold;color: #154BA0;background:#C2DEED;height: 25px;padding-left: 10px;
}
.header td {padding-left: 10px;}
.header a {color: #154BA0;}
.header input {background:none;vertical-align: middle;height: 16px;}
.category {font: 12px Arial, Tahoma !important;font: 11px Arial, Tahoma;color: #92A05A;height:20px;background-color: #FFFFD9;}
.category td {border-bottom: 1px solid #DEDEB8;}
.expire, .expire a:link, .expire a:visited {color: #999999;}
.default, .default a:link, .default a:visited {color: #000000;}
.checked, .checked a:link, .checked a:visited {color: #FF0000;}
.today, .today a:link, .today a:visited {color: #00BB00;}
#calendar_year {display: none;line-height: 130%;background: #FFFFFF;position: absolute;z-index: 10;}
#calendar_year .col {float: left;background: #FFFFFF;margin-left: 1px;border: 1px solid #86B9D6;padding: 4px;}
#calendar_month {display: none;background: #FFFFFF;line-height: 130%;border: 1px solid #86B9D6;padding: 4px;position: absolute;z-index: 11;}
.tableborder {background: white;border: 1px solid #86B9D6;}
#year,#month{padding-right:10px;background:url(attachments/month_0701/8200714125245.gif) no-repeat center right;}/*图片路径可以改成自己的*/
/*Date*/
</style>
<script>
//这段脚本如果你的页面里有,就可以去掉它们了
//欢迎访问我的网站queyang.com
var ie =navigator.appName=="Microsoft Internet Explorer"?true:false;
function $(objID){
 return document.getElementById(objID);
}
</script>
</head>
<body>
<!--记得哦,下面的代码得放在Body标签里,当然,放在页面最后面也可以(不过有可能会出现JS还未加载完毕时用户点击了下面的输入框,这样页面就会出错了。)-->
<script type="text/javascript">
var controlid = null;
var currdate = null;
var startdate = null;
var enddate  = null;
var yy = null;
var mm = null;
var hh = null;
var ii = null;
var currday = null;
var addtime = false;
var today = new Date();
var lastcheckedyear = false;
var lastcheckedmonth = false;
function _cancelBubble(event) {
 e = event ? event : window.event ;
 if(ie) {
  e.cancelBubble = true;
 } else {
  e.stopPropagation();
 }
}
function getposition(obj) {
 var r = new Array();
 r['x'] = obj.offsetLeft;
 r['y'] = obj.offsetTop;
 while(obj = obj.offsetParent) {
  r['x'] += obj.offsetLeft;
  r['y'] += obj.offsetTop;
 }
 return r;
}
function loadcalendar() {
 s = '';
 s += '<div id="calendar" style="display:none; position:absolute; z-index:9;" onclick="_cancelBubble(event)">';
 if (ie)
 {
  s += '<iframe width="200" height="160" src="about:blank" style="position: absolute;z-index:-1;"></iframe>';
 }
 s += '<div style="width: 200px;"><table class="tableborder" cellspacing="0" cellpadding="0" width="100%" style="text-align: center">';
 s += '<tr align="center" class="header"><td class="header"><a href="#" onclick="refreshcalendar(yy, mm-1);return false" title="上一月"><<</a></td><td colspan="5" style="text-align: center" class="header"><a href="#" onclick="showdiv('year');_cancelBubble(event);return false" title="点击选择年份" id="year"></a>  -  <a id="month" title="点击选择月份" href="#" onclick="showdiv('month');_cancelBubble(event);return false"></a></td><td class="header"><A href="#" onclick="refreshcalendar(yy, mm+1);return false" title="下一月">>></A></td></tr>';
金沙棋牌官方平台, s += '<tr class="category"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
 for(var i = 0; i < 6; i++) {
  s += '<tr class="altbg2">';
  for(var j = 1; j <= 7; j++)
   s += "<td id=d" + (i * 7 + j) + " height="19">0</td>";
  s += "</tr>";
 }
 s += '<tr id="hourminute"><td colspan="7" align="center"><input type="text" size="1" value="" id="hour" onKeyUp='this.value=this.value > 23 ? 23 : zerofill(this.value);controlid.value=controlid.value.replace(/\d+(:\d+)/ig, this.value+"$1")'> 点 <input type="text" size="1" value="" id="minute" onKeyUp='this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(<a href="file://\d+:)\d+/ig">\d+:)\d+/ig</a>, "$1"+this.value)'> 分</td></tr>';
 s += '</table></div></div>';
 s += '<div id="calendar_year" onclick="_cancelBubble(event)"><div class="col">';
 for(var k = 1930; k <= 2019; k++) {
  s += k != 1930 && k % 10 == 0 ? '</div><div class="col">' : '';
  s += '<a href="#" onclick="refreshcalendar(' + k + ', mm);$('calendar_year').style.display='none';return false"><span' + (today.getFullYear() == k ? ' class="today"' : '')

复制代码 代码如下:

好久没更新博客了,不是因为懒,是一到年底忙得不行,基本没有喘息去学习的时间,要坚持去做一件事情不容易,比如锻炼(买的器材现在全是灰)、减肥(还是那么肥)、看书(买了不少书还没细看)、coding(...)、写博客。

  • ' id="calendar_year_' + k + '">' + k + '</span></a><br />';
     }
     s += '</div></div>';
     s += '<div id="calendar_month" onclick="_cancelBubble(event)">';
     for(var k = 1; k <= 12; k++) {
      s += '<a href="#" onclick="refreshcalendar(yy, ' + (k - 1) + ');$('calendar_month').style.display='none';return false"><span' + (today.getMonth()+1 == k ? ' class="today"' : '')
  • ' id="calendar_month_' + k + '">' + k + ( k < 10 ? ' ' : '') + ' 月</span></a><br />';
     }
     s += '</div>';
     var nElement = document.createElement("div");
     nElement.innerHTML=s;
     document.getElementsByTagName("body")[0].appendChild(nElement);
    // document.write(s);
     document.onclick = function(event) {
      $('calendar').style.display = 'none';
      $('calendar_year').style.display = 'none';
      $('calendar_month').style.display = 'none';
     }
     $('calendar').onclick = function(event) {
      _cancelBubble(event);
      $('calendar_year').style.display = 'none';
      $('calendar_month').style.display = 'none';
     }
    }
    function parsedate(s) {
     /(d+)-(d+)-(d+)s*(d*):?(d*)/.exec(s);
     var m1 = (RegExp.$1 && RegExp.$1 > 1899 && RegExp.$1 < 2101) ? parseFloat(RegExp.$1) : today.getFullYear();
     var m2 = (RegExp.$2 && (RegExp.$2 > 0 && RegExp.$2 < 13)) ? parseFloat(RegExp.$2) : today.getMonth() + 1;
     var m3 = (RegExp.$3 && (RegExp.$3 > 0 && RegExp.$3 < 32)) ? parseFloat(RegExp.$3) : today.getDate();
     var m4 = (RegExp.$4 && (RegExp.$4 > -1 && RegExp.$4 < 24)) ? parseFloat(RegExp.$4) : 0;
     var m5 = (RegExp.$5 && (RegExp.$5 > -1 && RegExp.$5 < 60)) ? parseFloat(RegExp.$5) : 0;
     /(d+)-(d+)-(d+)s*(d*):?(d*)/.exec("0000-00-00 00:00");
     return new Date(m1, m2 - 1, m3, m4, m5);
    }
    function settime(d) {
     $('calendar').style.display = 'none';
     controlid.value = yy + "-" + zerofill(mm + 1) + "-" + zerofill(d) + (addtime ? ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value) : '');
    }
    function showcalendar(event, controlid1, addtime1, startdate1, enddate1) {
     controlid = controlid1;
     addtime = addtime1;
     startdate = startdate1 ? parsedate(startdate1) : false;
     enddate = enddate1 ? parsedate(enddate1) : false;
     currday = controlid.value ? parsedate(controlid.value) : today;
     hh = currday.getHours();
     ii = currday.getMinutes();
     var p = getposition(controlid);
     $('calendar').style.display = 'block';
     $('calendar').style.left = p['x']+'px';
     $('calendar').style.top = (p['y'] + 20)+'px';
     _cancelBubble(event);
     refreshcalendar(currday.getFullYear(), currday.getMonth());
     if(lastcheckedyear != false) {
      $('calendar_year_' + lastcheckedyear).className = 'default';
      $('calendar_year_' + today.getFullYear()).className = 'today';
     }
     if(lastcheckedmonth != false) {
      $('calendar_month_' + lastcheckedmonth).className = 'default';
      $('calendar_month_' + (today.getMonth() + 1)).className = 'today';
     }
     $('calendar_year_' + currday.getFullYear()).className = 'checked';
     $('calendar_month_' + (currday.getMonth() + 1)).className = 'checked';
     $('hourminute').style.display = addtime ? '' : 'none';
     lastcheckedyear = currday.getFullYear();
     lastcheckedmonth = currday.getMonth() + 1;
    }
    function refreshcalendar(y, m) {
     var x = new Date(y, m, 1);
     var mv = x.getDay();
     var d = x.getDate();
     var dd = null;
     yy = x.getFullYear();
     mm = x.getMonth();
     $("year").innerHTML = yy;
     $("month").innerHTML = mm + 1 > 9  ? (mm + 1) : '0' + (mm + 1);
     for(var i = 1; i <= mv; i++) {
      dd = $("d" + i);
      dd.innerHTML = " ";
      dd.className = "";
     }
     while(x.getMonth() == mm) {
      dd = $("d" + (d + mv));
      dd.innerHTML = '<a href="###" onclick="settime(' + d + ');return false">' + d + '</a>';
      if(x.getTime() < today.getTime() || (enddate && x.getTime() > enddate.getTime()) || (startdate && x.getTime() < startdate.getTime())) {
       dd.className = 'expire';
      } else {
       dd.className = 'default';
      }
      if(x.getFullYear() == today.getFullYear() && x.getMonth() == today.getMonth() && x.getDate() == today.getDate()) {
       dd.className = 'today';
       dd.firstChild.title = '今天';
      }
      if(x.getFullYear() == currday.getFullYear() && x.getMonth() == currday.getMonth() && x.getDate() == currday.getDate()) {
       dd.className = 'checked';
      }
      x.setDate(++d);
     }
     while(d + mv <= 42) {
      dd = $("d" + (d + mv));
      dd.innerHTML = " ";
      d++;
     }
     if(addtime) {
      $('hour').value = zerofill(hh);
      $('minute').value = zerofill(ii);
     }
    }
    function showdiv(id) {
     var p = getposition($(id));
     $('calendar_' + id).style.left = p['x']+'px';
     $('calendar_' + id).style.top = (p['y'] + 16)+'px';
     $('calendar_' + id).style.display = 'block';
    }
    function zerofill(s) {
     var s = parseFloat(s.toString().replace(/(^[s0]+)|(s+$)/g, ''));
     s = isNaN(s) ? 0 : s;
     return (s < 10 ? '0' : '') + s.toString();
    }
    loadcalendar();absolutecellpadding
    </script>
    选择日期:<input name="member.birth"  type="text" value="1982-1-1" size="14" readonly="readonly" onclick="showcalendar(event, this);" onfocus="showcalendar(event, this);if(this.value=='0000-00-00')this.value=''" />
    </body>
    </html>

<html>
<head>
<title>很漂亮、兼容火狐的Js日期选择,自动填充到输入框</title>
<meta http-equiv="content-Type" content="text/html;charset=gb2312">
<style type="text/css">
body{font-size:12px;font-family:Verdana,Arial,"宋体";}
a:link {color:#464646;text-decoration:none;}
a:visited {color:#464646;text-decoration:none;}
a:hover{color:#ed145b;text-decoration:underline;}
a:active{color:#ed145b;text-decoration:underline;}
td{font-size:12px}
/*/*/
/*DateCSS样式*/
.header {font: 12px Arial, Tahoma !important;font-weight: bold !important;font: 11px Arial, Tahoma;font-weight: bold;color: #154BA0;background:#C2DEED;height: 25px;padding-left: 10px;
}
.header td {padding-left: 10px;}
.header a {color: #154BA0;}
.header input {background:none;vertical-align: middle;height: 16px;}
.category {font: 12px Arial, Tahoma !important;font: 11px Arial, Tahoma;color: #92A05A;height:20px;background-color: #FFFFD9;}
.category td {border-bottom: 1px solid #DEDEB8;}
.expire, .expire a:link, .expire a:visited {color: #999999;}
.default, .default a:link, .default a:visited {color: #000000;}
.checked, .checked a:link, .checked a:visited {color: #FF0000;}
.today, .today a:link, .today a:visited {color: #00BB00;}
#calendar_year {display: none;line-height: 130%;background: #FFFFFF;position: absolute;z-index: 10;}
#calendar_year .col {float: left;background: #FFFFFF;margin-left: 1px;border: 1px solid #86B9D6;padding: 4px;}
#calendar_month {display: none;background: #FFFFFF;line-height: 130%;border: 1px solid #86B9D6;padding: 4px;position: absolute;z-index: 11;}
.tableborder {background: white;border: 1px solid #86B9D6;}
#year,#month{padding-right:10px;}
</style>
<script language="javascript">
//下面的代码段如果你页面里有,可以去掉
var ie =navigator.appName=="Microsoft Internet Explorer"?true:false;
function $(objID){
return document.getElementById(objID);
}
</script>
</head>
<body>

年底又要开始新项目了金沙棋牌官方平台 8,看着自己负责的项目一个个的上线又一个个的下线。金沙棋牌官方平台 9

<script type="text/javascript">
var controlid = null;
var currdate = null;
var startdate = null;
var enddate = null;
var yy = null;
var mm = null;
var hh = null;
var ii = null;
var currday = null;
var addtime = false;
var today = new Date();
var lastcheckedyear = false;
var lastcheckedmonth = false;
function _cancelBubble(event) {
e = event ? event : window.event ;
if(ie) {
e.cancelBubble = true;
} else {
e.stopPropagation();
}
}
function getposition(obj) {
var r = new Array();
r['x'] = obj.offsetLeft;
r['y'] = obj.offsetTop;
while(obj = obj.offsetParent) {
r['x'] += obj.offsetLeft;
r['y'] += obj.offsetTop;
}
return r;
}
function loadcalendar() {
s = '';
s += '<div id="calendar" style="display:none; position:absolute; z-index:9;" onclick="_cancelBubble(event)">';
if (ie)
{
s += '<iframe width="200" height="160" src="about:blank" style="position: absolute;z-index:-1;"></iframe>';
}
s += '<div style="width: 200px;"><table class="tableborder" cellspacing="0" cellpadding="0" width="100%" style="text-align: center">';
///
s += '<tr align="center" class="header"><td class="header"><a href="#" onclick="refreshcalendar(yy, mm-1);return false" title="上一月"><<</a></td><td colspan="5" style="text-align: center" class="header"><a href="#" onclick="showdiv('year');_cancelBubble(event);return false" title="点击选择年份" id="year"></a> - <a id="month" title="点击选择月份" href="#" onclick="showdiv('month');_cancelBubble(event);return false"></a></td><td class="header"><A href="#" onclick="refreshcalendar(yy, mm+1);return false" title="下一月">>></A></td></tr>';
s += '<tr class="category"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
for(var i = 0; i < 6; i++) {
s += '<tr class="altbg2">';
for(var j = 1; j <= 7; j++)
s += "<td id=d" + (i * 7 + j) + " height="19">0</td>";
s += "</tr>";
}
s += '<tr id="hourminute"><td colspan="7" align="center"><input type="text" size="1" value="" id="hour" onKeyUp='this.value=this.value > 23 ? 23 : zerofill(this.value);controlid.value=controlid.value.replace(/\d+(:\d+)/ig, this.value+"$1")'> 点 <input type="text" size="1" value="" id="minute" onKeyUp='this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(\d+:)\d+/ig, "$1"+this.value)'> 分</td></tr>';
s += '</table></div></div>';///
s += '<div id="calendar_year" onclick="_cancelBubble(event)"><div class="col">';
for(var k = 1930; k <= 2019; k++) {
s += k != 1930 && k % 10 == 0 ? '</div><div class="col">' : '';
s += '<a href="#" onclick="refreshcalendar(' + k + ', mm);$('calendar_year').style.display='none';return false"><span' + (today.getFullYear() == k ? ' class="today"' : '')

 

  • ' id="calendar_year_' + k + '">' + k + '</span></a><br />';
    }
    s += '</div></div>';
    s += '<div id="calendar_month" onclick="_cancelBubble(event)">';
    for(var k = 1; k <= 12; k++) {
    s += '<a href="#" onclick="refreshcalendar(yy, ' + (k - 1) + ');$('calendar_month').style.display='none';return false"><span' + (today.getMonth()+1 == k ? ' class="today"' : '')
  • ' id="calendar_month_' + k + '">' + k + ( k < 10 ? ' ' : '') + ' 月</span></a><br />';
    }
    s += '</div>';
    var nElement = document.createElement("div");
    nElement.innerHTML=s;
    document.getElementsByTagName("body")[0].appendChild(nElement);
    //document.write(s);
    document.onclick = function(event) {
    $('calendar').style.display = 'none';
    $('calendar_year').style.display = 'none';
    $('calendar_month').style.display = 'none';
    }
    $('calendar').onclick = function(event) {
    _cancelBubble(event);
    $('calendar_year').style.display = 'none';
    $('calendar_month').style.display = 'none';
    }
    }
    function parsedate(s) {
    /(d+)-(d+)-(d+)s*(d*):?(d*)/.exec(s);
    var m1 = (RegExp.$1 && RegExp.$1 > 1899 && RegExp.$1 < 2101) ? parseFloat(RegExp.$1) : today.getFullYear();
    var m2 = (RegExp.$2 && (RegExp.$2 > 0 && RegExp.$2 < 13)) ? parseFloat(RegExp.$2) : today.getMonth() + 1;
    var m3 = (RegExp.$3 && (RegExp.$3 > 0 && RegExp.$3 < 32)) ? parseFloat(RegExp.$3) : today.getDate();
    var m4 = (RegExp.$4 && (RegExp.$4 > -1 && RegExp.$4 < 24)) ? parseFloat(RegExp.$4) : 0;
    var m5 = (RegExp.$5 && (RegExp.$5 > -1 && RegExp.$5 < 60)) ? parseFloat(RegExp.$5) : 0;
    /(d+)-(d+)-(d+)s*(d*):?(d*)/.exec("0000-00-00 00:00");
    return new Date(m1, m2 - 1, m3, m4, m5);
    }
    function settime(d) {
    $('calendar').style.display = 'none';
    controlid.value = yy + "-" + zerofill(mm + 1) + "-" + zerofill(d) + (addtime ? ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value) : '');
    }
    function showcalendar(event, controlid1, addtime1, startdate1, enddate1) {
    controlid = controlid1;
    addtime = addtime1;
    startdate = startdate1 ? parsedate(startdate1) : false;
    enddate = enddate1 ? parsedate(enddate1) : false;
    currday = controlid.value ? parsedate(controlid.value) : today;
    hh = currday.getHours();
    ii = currday.getMinutes();
    var p = getposition(controlid);
    $('calendar').style.display = 'block';
    $('calendar').style.left = p['x']+'px';
    $('calendar').style.top = (p['y'] + 20)+'px';
    _cancelBubble(event);
    refreshcalendar(currday.getFullYear(), currday.getMonth());
    if(lastcheckedyear != false) {
    $('calendar_year_' + lastcheckedyear).className = 'default';
    $('calendar_year_' + today.getFullYear()).className = 'today';
    }
    if(lastcheckedmonth != false) {
    $('calendar_month_' + lastcheckedmonth).className = 'default';
    $('calendar_month_' + (today.getMonth() + 1)).className = 'today';
    }
    $('calendar_year_' + currday.getFullYear()).className = 'checked';
    $('calendar_month_' + (currday.getMonth() + 1)).className = 'checked';
    $('hourminute').style.display = addtime ? '' : 'none';
    lastcheckedyear = currday.getFullYear();
    lastcheckedmonth = currday.getMonth() + 1;
    }
    function refreshcalendar(y, m) {
    var x = new Date(y, m, 1);
    var mv = x.getDay();
    var d = x.getDate();
    var dd = null;
    yy = x.getFullYear();
    mm = x.getMonth();
    $("year").innerHTML = yy;
    $("month").innerHTML = mm + 1 > 9 ? (mm + 1) : '0' + (mm + 1);
    for(var i = 1; i <= mv; i++) {
    dd = $("d" + i);
    dd.innerHTML = " ";
    dd.className = "";
    }
    while(x.getMonth() == mm) {
    dd = $("d" + (d + mv));
    dd.innerHTML = '<a href="###" onclick="settime(' + d + ');return false">' + d + '</a>';
    if(x.getTime() < today.getTime() || (enddate && x.getTime() > enddate.getTime()) || (startdate && x.getTime() < startdate.getTime())) {
    dd.className = 'expire';
    } else {
    dd.className = 'default';
    }
    if(x.getFullYear() == today.getFullYear() && x.getMonth() == today.getMonth() && x.getDate() == today.getDate()) {
    dd.className = 'today';
    dd.firstChild.title = '今天';
    }
    if(x.getFullYear() == currday.getFullYear() && x.getMonth() == currday.getMonth() && x.getDate() == currday.getDate()) {
    dd.className = 'checked';
    }
    x.setDate(++d);
    }
    while(d + mv <= 42) {
    dd = $("d" + (d + mv));
    dd.innerHTML = " ";
    d++;
    }
    if(addtime) {
    $('hour').value = zerofill(hh);
    $('minute').value = zerofill(ii);
    }
    }
    function showdiv(id) {
    var p = getposition($(id));
    $('calendar_' + id).style.left = p['x']+'px';
    $('calendar_' + id).style.top = (p['y'] + 16)+'px';
    $('calendar_' + id).style.display = 'block';
    }
    function zerofill(s) {
    var s = parseFloat(s.toString().replace(/(^[s0]+)|(s+$)/g, ''));
    s = isNaN(s) ? 0 : s;
    return (s < 10 ? '0' : '') + s.toString();
    }
    loadcalendar();
    </script>
    用法演示:<br>请选择日期:<input name="member.birth" type="text" value="2008-5-19" size="14" readonly onclick="showcalendar(event,this);" onfocus="showcalendar(event, this);if(this.value=='0000-00-00')this.value=''">
    </body>
    </html>

这次开始的项目是PC版的,貌似有2年没正儿八经的折腾PC端了,本来打算让实习生干的,尼玛,周三拿到需求要周五上线,逗我呢,另外一个项目还在同时进行......苦逼。

代码如下: html head title很漂亮、兼容火狐的Js日期选择,自动填充到输入框/title meta http-equiv="content-Type" content="text/html;charset=gb231...

言归正传,这次功能中有个选择日期段的功能,本来不麻烦的事情,但是PM非要参照另外一个网站的效果来做,把别人代码扒下来一看,我去,08年的插件,很多功能不能满足当前,PM非要那效果,时间又TM有限,就又找了个国外的插件daterangepicker,基于bootstrap,跟需求长得很像,功能非常强大,需求都能满足,但是...但是,PM和测试说不好用。。。折腾了半天源代码,优化了下,时间来不及只能凑合用着。

重新动手写了个。依赖jquery和moment.js(主要处理日期,如果自己处理也可以不需要),

先看效果图

金沙棋牌官方平台 10

使用方法:

var daterangepicker = new DateRangePicker();
daterangepicker.init({
    "ele": $("#daterange"),
    "pos":"left",
    "min_date": "1990-01-01",
    "format": "YYYY:MM:DD",
    "updateDateFn":function(){
        console.log(daterangepicker.getDate())
    }
});

 

基本思路是:

创建一个日期选择构造函数

function DateRangePicker() {
this.start_picker = null;
this.end_picker = null;
}

初始化日期构造函数,日期段由两个单独的日期选择组成,当起始日期和结束日期变化时要调用构造函数的updateDate方法,通知日期发生了变化。

DateRangePicker.prototype.init = function(opts) {
    var self = this;
    this.opts = $.extend({
        "pos":"left",//日历位置,靠左或靠右
        "min_date":"1970-01-01",//最小日期
        "updateDateFn":function(){//日期更新回调

        }
    }, opts || {});
    this.createCalendarWrap();
    this.$wrap=this.opts.ele.parents(".ui-datepicker");
    this.start_picker = new DatePicker();//起始日期日历
    this.end_picker = new DatePicker();//结束日期日历
    this.start_picker.init({
        "container": this.$wrap.find(".calendar-container"),
        "min_date":self.opts.min_date,
        "yearOffset": 20,
        "updateCallback": function(){
            self.updateDate();
        }
    });
    this.end_picker.init({
        "container": this.$wrap.find(".calendar-container2"),
        "yearOffset": 20,
        "min_date":self.opts.min_date,
        "updateCallback": function(){
            self.updateDate();
        }
    });
    this.bindEvent();
};

处理日期发生变化的情况,比如起始日期大于结束日期,要进行互换。

DateRangePicker.prototype.updateDate = function() {
    var self = this;
    var start_date = moment(self.start_picker.currentDate).format(self.opts.format);
    var end_date = moment(self.end_picker.currentDate).format(self.opts.format);
    var start_date_time=new Date(self.start_picker.currentDate).getTime();
    var end_date_time=new Date(self.end_picker.currentDate).getTime();
    if(start_date_time>new Date().getTime()){
        self.start_picker.setCurrentDate(new Date());
    }
    if(end_date_time>new Date().getTime()){
        self.end_picker.setCurrentDate(new Date());
    }
    if(start_date_time>end_date_time){
        self.opts.ele.val(end_date + "~" + start_date);
    }else{
        self.opts.ele.val(start_date + "~" + end_date);
    }
    $(".ui-daterangepicker-range li").removeClass("active");
    self.opts.updateDateFn.call(null,this.getDate());//日期更新后重新获取当前的起始和结束日期
};

获取起始和结束日期

//获取起始日期和结束日期段,起始日期若大于结束日期则互换
DateRangePicker.prototype.getDate = function() {
    var start_date=Math.min(this.start_picker.currentDate.getTime(),this.end_picker.currentDate.getTime());
    var end_date=Math.max(this.start_picker.currentDate.getTime(),this.end_picker.currentDate.getTime());
    start_date=moment(start_date).format(this.opts.format);
    end_date=moment(end_date).format(this.opts.format);
    return {
        "start_date":start_date,
        "end_date": end_date
    };
};

提供动态设置当前起始日期和结束日期的方法

//设置起始日期和结束日期
DateRangePicker.prototype.setDate = function(start_date, end_date) {
    this.start_picker.setCurrentDate(new Date(start_date));
    this.end_picker.setCurrentDate(new Date(end_date));
    this.updateDate();
};

创建一个容器,因为日期选择要刚好在日期文本框下面,在日期文本框外面包一层方便定位。

//创建日期段容器
DateRangePicker.prototype.createCalendarWrap = function() {
    var $parent=this.opts.ele.parents(".ui-datepicker");
    var h=$parent.height(),w=$parent.width();
    var wrap = '<div class="ui-daterangepicker-wrap" style="top:'+h+'px;'+this.opts.pos+':0"><div class="ui-calendar"><p class="calendar-title">开始日期</p><div class="calendar-container"></div></div>' +
        '<div class="ui-calendar"><p class="calendar-title">结束日期</p><div class="calendar-container2"></div></div>' +
        '<div class="ui-daterangepicker-range"><ul>' +
        '<li range-key="今日">今日</li>' +
        '<li range-key="昨日">昨日</li>' +
        '<li range-key="最近7日">最近7日</li>' +
        '<li range-key="最近30日">最近30日</li>' +
        '</ul>' +
        '</div></div>';
    $parent.append(wrap);
};

接下来是单个日期选择的处理

定义构造函数和初始化

function DatePicker() {
    this.opts = null;
    this.today = new Date(); //今天
    this.todayDate=this.today.getDate();
    this.currentDate = new Date(); //当前选中日期
}
DatePicker.prototype.init = function(opts) {
    var opts = $.extend({
        'min_date':"1970-01-01",
        "yearOffset": 20//默认往前推20年
    }, opts || {});
    this.opts = opts;
    this.renderCalendar();
    this.bindEvent();
};

事件处理

DatePicker.prototype.bindEvent = function() {
    var self = this;
    self.opts.container.on("change", ".year-select", function() {
        self.renderSelectedDate();
    });
    //选中月份
    self.opts.container.on("change", ".month-select", function() {
        self.renderSelectedDate();
    });
    //下一月
    self.opts.container.on("click", ".next-btn", function(e) {
        e.stopPropagation();
        var cur_date =self.currentDate.setMonth(self.currentDate.getMonth()+1);;
        self.setCurrentDate(cur_date);
    });
    //上一月
    self.opts.container.on("click", ".prev-btn", function(e) {
        e.stopPropagation();
        var cur_date = self.currentDate.setMonth(self.currentDate.getMonth()-1);
        self.setCurrentDate(cur_date);
    });
    //选择日历中某一天
    self.opts.container.on("click", ".date-item", function() {
        if (!$(this).hasClass("disabled")) {
            var _day = $(this).attr("date");
            var cur_date = self.currentDate.setDate(_day);
            self.setCurrentDate(cur_date);
        }
    });
};

定义临时存储的当前日期,默认日期是今天,但是选择的时候当前日期会变化。

//临时被选中的日期
DatePicker.prototype.tempActiveDate=(function(){
    var _date=new Date();
    return {
        getDate: function() {
            return _date;
        },
        setDate:function(date){
            _date=new Date(date);
        }
    };
})();

年月下拉框变化时更新日期

//设置下拉框选中的日期
DatePicker.prototype.renderSelectedDate = function() {
    var _year = this.opts.container.find(".year-select").val();
    var _month = this.opts.container.find(".month-select").val();
    var _day = this.currentDate.getDate();
    var cur_date = new Date(_year, _month, _day);
    this.setCurrentDate(cur_date);
};

渲染日历框架,日历固定为42格,7列6行,星期从一到天

//渲染日历框架
DatePicker.prototype.renderCalendar = function() {
    var calendar_header = this.renderHeader();
    var calendar_days = '<table class="calendar-table"><thead><tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr></thead>';
    var calendar_body = '<tbody class="calendar_body">';
    for (var i = 0; i < 6; i++) {
        calendar_body += '<tr><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td></tr>';
    }
    calendar_body + '</tbody></table>';
    this.opts.container.html(calendar_header + calendar_days + calendar_body);
    this.renderCalendarData();
};

渲染日历的头部,包括上月、下月按钮,年月的下拉框

//渲染日历头部
DatePicker.prototype.renderHeader = function() {
    var _year = this.today.getFullYear();
    var _month = this.today.getMonth() + 1;
    var current_year = this.currentDate.getFullYear();
    var current_month = this.currentDate.getMonth();
    var monthArr = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"];
    var min_year=(new Date(this.opts.min_date)).getFullYear();//最小年份
    var start_year=current_year - this.opts.yearOffset>=min_year?current_year - this.opts.yearOffset:min_year;//下拉框起始年份
    var yearSelect="";
    //如果已经是最小日期,不显示上月按钮
    if (current_year <= min_year && current_month <= 0) {
        yearSelect+='<select class="year-select">';
    }else{
        yearSelect = '< <select class="year-select">';
    }
    for (var i =start_year; i <= _year; i++) {
        if (i == current_year) {
            yearSelect += '<option value="' + i + '" selected>' + i + '</option>';
        } else {
            yearSelect += '<option value="' + i + '">' + i + '</option>';
        }
    }
    yearSelect += '</select>';
    var monthSelect = '<select class="month-select">';
    for (var i = 0; i < 12; i++) {
        var state="";
        if (current_year < _year) {
            if (i == current_month) {
                state="selected";
            }
        }else if (current_year == _year) {
            if(i==current_month){
                state="selected";
            }else{
                state="disabled";
            }
        }else{
            state="disabled";
        }
        monthSelect += '<option value="' + i + '" '+state+'>' + monthArr[i] + '月</option>';
    }
    if (current_year >= _year && current_month+1 >= _month) {
        monthSelect += '</select>';
    }else{
        monthSelect += '</select>>';
    }
    return "<div class='calendar_header'>" + yearSelect + monthSelect + "</div>";
};

 

 

//渲染日历数据
DatePicker.prototype.renderCalendarData = function() {
    var self = this;
    var _year = this.currentDate.getFullYear(); //当前年
    var _month = this.currentDate.getMonth() + 1; //当前月
    var _firstDay = new Date(_year, _month - 1, 1); //当前月第一天
    var tds = this.opts.container.find(".calendar_body td");
    var header = self.renderHeader();
    this.opts.container.find(".calendar_header").html(header);
    tds.each(function(index, item) {
        var _thisDate = new Date(_year, _month - 1, index + 1 - _firstDay.getDay());
        var _thisDay = _thisDate.getDate();
        var _thisMonth = _thisDate.getMonth() + 1;
        var _thisDateTime=_thisDate.getTime();
        $(item).html(_thisDay).attr("date", _thisDay).removeClass("active").removeClass("disabled").removeClass("today");
        //当前月并且当前选中日期高亮
        if (_thisDay == self.tempActiveDate.getDate().getDate() && _thisMonth == _month) {
            $(item).addClass("active");
        }
        //今天日期样式
        if (_thisDay == self.todayDate) {
            $(item).addClass("today");
        }
        //非当前月或者大于今天的日期禁用
        if (_thisMonth !== _month || _thisDateTime>self.today.getTime()) {
            $(item).addClass("disabled").removeClass('active today');
        }
        //如果选择的日期大于今天,则日期重置
        if (_thisDateTime>self.today.getTime() && _thisDay == self.todayDate) {
            $(item).addClass("active");
            self.currentDate = _thisDate;
        }
    });
};
//设置当前日期
DatePicker.prototype.setCurrentDate = function(date) {
    this.tempActiveDate.setDate(date);
    this.currentDate = this.tempActiveDate.getDate();
    this.renderCalendarData();
    if(this.opts.updateCallback){
        this.opts.updateCallback.call(null,this.currentDate);
    }
};

 

js完整代码(2017-02-16更新)

function DatePicker() {
this.opts = null;
this.today = new Date(); //今天
this.todayDate=this.today.getDate();
this.currentDate = new Date(); //当前选中日期
}
DatePicker.prototype.init = function(opts) {
var opts = $.extend({
'min_date':"1970-01-01",
"yearOffset": 20//默认往前推20年
}, opts || {});
this.opts = opts;
this.renderCalendar();
this.bindEvent();
};
DatePicker.prototype.bindEvent = function() {
var self = this;
self.opts.container.on("change", ".year-select", function() {
self.renderSelectedDate();
});
//选中月份
self.opts.container.on("change", ".month-select", function() {
self.renderSelectedDate();
});
//下一月
self.opts.container.on("click", ".next-btn", function(e) {
e.stopPropagation();
var cur_date =self.currentDate.setMonth(self.currentDate.getMonth()+1);
self.setCurrentDate(cur_date);
});
//上一月
self.opts.container.on("click", ".prev-btn", function(e) {
e.stopPropagation();
var cur_date = self.currentDate.setMonth(self.currentDate.getMonth()-1);
self.setCurrentDate(cur_date);
});
//选择日历中某一天
self.opts.container.on("click", ".date-item", function() {
if (!$(this).hasClass("disabled")) {
var _day = $(this).attr("date");
var cur_date = self.currentDate.setDate(_day);
self.setCurrentDate(cur_date);
}
});
};
//临时被选中的日期
DatePicker.prototype.tempActiveDate=(function(){
var _date=new Date();
return {
getDate: function() {
return _date;
},
setDate:function(date){
_date=new Date(date);
}
};
})();
//设置下拉框选中的日期
DatePicker.prototype.renderSelectedDate = function() {
var _year = this.opts.container.find(".year-select").val();
var _month = this.opts.container.find(".month-select").val();
var _day = this.currentDate.getDate();
var cur_date = new Date(_year, _month, _day);
this.setCurrentDate(cur_date);
};
//渲染日历框架
DatePicker.prototype.renderCalendar = function() {
var calendar_header = this.renderHeader();
var calendar_days = '<table class="calendar-table"><thead><tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr></thead>';
var calendar_body = '<tbody class="calendar_body">';
for (var i = 0; i < 6; i++) {
calendar_body += '<tr><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td><td class="date-item"></td></tr>';
}
calendar_body + '</tbody></table>';
this.opts.container.html(calendar_header + calendar_days + calendar_body);
this.renderCalendarData();
};
//渲染日历头部
DatePicker.prototype.renderHeader = function() {
var _year = this.today.getFullYear();
var _month = this.today.getMonth() + 1;
var current_year = this.currentDate.getFullYear();
var current_month = this.currentDate.getMonth();
var monthArr = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"];
var min_year=(new Date(this.opts.min_date.replace(/-/g,"/"))).getFullYear();//最小年份
var start_year=current_year - this.opts.yearOffset>=min_year?current_year - this.opts.yearOffset:min_year;//下拉框起始年份
var yearSelect="";
//如果已经是最小日期,不显示上月按钮
if (current_year <= min_year && current_month <= 0) {
yearSelect+='<select class="year-select">';
}else{
yearSelect = '<span class="prev-btn"><</span> <select class="year-select">';
}
for (var i =start_year; i <= _year; i++) {
if (i == current_year) {
yearSelect += '<option value="' + i + '" selected>' + i + '</option>';
} else {
yearSelect += '<option value="' + i + '">' + i + '</option>';
}
}
yearSelect += '</select>';
var monthSelect = '<select class="month-select">';
for (var i = 0; i < 12; i++) {
var state="";
if (current_year < _year) {
if (i == current_month) {
state="selected";
}
}else if (current_year == _year) {
if(i==current_month){
state="selected";
}else if(i>_month-1){
state="disabled";
}
}else{
state="disabled";
}
monthSelect += '<option value="' + i + '" '+state+'>' + monthArr[i] + '月</option>';
}
if (current_year >= _year && current_month+1 >= _month) {
monthSelect += '</select>';
}else{
monthSelect += '</select><span class="next-btn">></span>';
}
return "<div class='calendar_header'>" + yearSelect + monthSelect

  • "</div>";
    };
    //渲染日历数据
    DatePicker.prototype.renderCalendarData = function() {
    var self = this;
    var _year = this.currentDate.getFullYear(); //当前年
    var _month = this.currentDate.getMonth()+1; //当前月
    var _firstDay = new Date(_year, _month - 1, 1); //当前月第一天
    var _lastDay=new Date(_year,_month+1,0).getDate();//当前月最后一天
    var tds = this.opts.container.find(".calendar_body td");
    var header = self.renderHeader();
    this.opts.container.find(".calendar_header").html(header);
    tds.each(function(index, item) {
    var _thisDate = new Date(_year, _month - 1, index + 1 - _firstDay.getDay());
    var _thisYear=_thisDate.getFullYear();
    var _thisDay = _thisDate.getDate();
    var _thisMonth = _thisDate.getMonth() + 1;
    var _thisDateTime=_thisDate.getTime();
    $(item).html(_thisDay).attr("date", _thisDay).removeClass("active").removeClass("disabled").removeClass("today");
    //当前月并且当前选中日期高亮
    if (_thisDay == self.tempActiveDate.getDate().getDate()) {
    $(item).addClass("active");
    }
    //非当前月或者大于今天的日期禁用

if (_year!=_thisYear||_year == _thisYear && _thisMonth != _month || _year == _thisYear && _thisMonth == _month-1 && _thisDay > _lastDay || self.today.getTime() < new Date(_thisYear, _thisMonth-1, _thisDay).getTime()) {
$(item).addClass("disabled").removeClass('active today');
}
//处理跨年边界值,比如1990年1月显示的日期实际是1989年12月的日期
if (_year == _thisYear + 1 && new Date(_thisYear, _thisMonth-1, _thisDay).getTime()<_firstDay.getTime()) {
$(item).addClass("disabled").removeClass('active today');
}
//今天日期样式
if (_thisDate.getTime() == new Date(self.today.getFullYear(),self.today.getMonth(),self.today.getDate()).getTime()) {
$(item).addClass("today");
}
//如果选择的日期大于今天,则日期重置
if (_thisDateTime>self.today.getTime() && _thisDay == self.todayDate) {
$(item).addClass("active");
self.currentDate = _thisDate;
}
});
};
//设置当前日期
DatePicker.prototype.setCurrentDate = function(date, opt_notrigger) {
this.tempActiveDate.setDate(date);
this.currentDate = this.tempActiveDate.getDate();
this.renderCalendarData();
if(!opt_notrigger&&this.opts.updateCallback){
this.opts.updateCallback.call(null,this.currentDate);
}
};

//日期段由两个单独日期实例组成
function DateRangePicker() {
this.start_picker = null;
this.end_picker = null;
}
DateRangePicker.prototype.init = function(opts) {
var self = this;
this.opts = $.extend({
"pos":"left",//日历位置,靠左或靠右
"min_date":"1970-01-01",//最小日期
"confirmDateFn":function(){//日期更新回调

}
}, opts || {});
this.createCalendarWrap();
this.$wrap=this.opts.ele.parents(".ui-datepicker");
this.start_picker = new DatePicker();
this.end_picker = new DatePicker();
this.start_picker.init({
"container": this.$wrap.find(".calendar-container"),
"min_date":self.opts.min_date,
"yearOffset": self.opts.yearOffset,
"updateCallback": function(){
self.updateDate();
}
});
this.end_picker.init({
"container": this.$wrap.find(".calendar-container2"),
"yearOffset": self.opts.yearOffset,
"min_date":self.opts.min_date,
"updateCallback": function(){
self.updateDate();
}
});
this.bindEvent();
};
DateRangePicker.prototype.bindEvent = function() {
var self = this;
var start_picker = self.start_picker,
end_picker = self.end_picker;
var showStart, showEnd;
this.opts.ele.on("focus",function(){
self.$wrap.find(".ui-daterangepicker-wrap").show();
showStart = self.start_picker.currentDate.getTime();
showEnd = self.end_picker.currentDate.getTime();
});
this.$wrap.on("click", "[range-key]", function() {
var _year = start_picker.currentDate.getFullYear();
var _month = start_picker.currentDate.getMonth();
var range = $(this).attr("range-key");
var start_day = start_picker.todayDate,
end_day = new Date();
switch (range) {
case "今日":
start_day = new Date(moment());
break;
case "昨日":
start_day = new Date(moment().subtract(1, 'days'));
end_day=new Date(moment().subtract(1, 'days'));
break;
case "最近7日":
start_day = new Date(moment().subtract(6, 'days'));
break;
case "最近30日":
start_day = new Date(moment().subtract(29, 'days'));
break;
}
self.setDate(start_day,end_day);
$(this).addClass("active").siblings("[range-key]").removeClass("active");
});
this.$wrap.on("click", ".range-confirmBtn", function() {
var start_day = start_picker.currentDate,
end_day = end_picker.currentDate;
showStart = null, showEnd = null;
self.$wrap.find(".ui-daterangepicker-wrap").hide();
self.setDate(start_day, end_day);
self.opts.confirmDateFn();
});
this.$wrap.on("click", ".range-cancel", function() {
self.$wrap.find(".ui-daterangepicker-wrap").hide();
if (showStart != null && showEnd != null) {
self.setDate(showStart, showEnd);
}
});
$("html").on("click",function(e){
var $target=$(e.target);
if($target.closest(".ui-daterangepicker-wrap").length==0&&$target[0]!=self.opts.ele[0]){
if (self.$wrap.find(".ui-daterangepicker-wrap").is(":visible")) {
var cur_daterange=self.getDate();
var cur_startTime=new Date(cur_daterange.start_date).getTime();
var cur_endTime=new Date(cur_daterange.end_date).getTime();
if(cur_startTime!=showStart||cur_endTime!=showEnd){
e.preventDefault();
e.stopPropagation();
self.opts.confirmDateFn();
}
self.$wrap.find(".ui-daterangepicker-wrap").hide();
}
}
});
};
DateRangePicker.prototype.updateDate = function(is_empty) {
var self = this;
var start_date = moment(self.start_picker.currentDate).format(self.opts.format);
var end_date = moment(self.end_picker.currentDate).format(self.opts.format);
var start_date_time=new Date(self.start_picker.currentDate).getTime();
var end_date_time=new Date(self.end_picker.currentDate).getTime();
if(start_date_time>new Date().getTime()){
self.start_picker.setCurrentDate(new Date(),true);
}
if(end_date_time>new Date().getTime()){
self.end_picker.setCurrentDate(new Date(),true);
}
if (!is_empty) {
if (start_date_time > end_date_time) {
self.opts.ele.val(end_date + "~" + start_date);
} else {
self.opts.ele.val(start_date + "~" + end_date);
}
}
$(".ui-daterangepicker-range li").removeClass("active");
};
//获取起始日期和结束日期段,起始日期若大于结束日期则互换
DateRangePicker.prototype.getDate = function() {
var start_date=Math.min(this.start_picker.currentDate.getTime(),this.end_picker.currentDate.getTime());
var end_date=Math.max(this.start_picker.currentDate.getTime(),this.end_picker.currentDate.getTime());
start_date=moment(start_date).format(this.opts.format);
end_date=moment(end_date).format(this.opts.format);
return {
"start_date":start_date,
"end_date": end_date
};
};
//设置起始日期和结束日期
DateRangePicker.prototype.setDate = function(start_date, end_date,is_empty) {
if(typeof(start_date)=="string"){
start_date=start_date.replace(/-/g,"/");
}
if(typeof(end_date)=="string"){
end_date=end_date.replace(/-/g,"/");
}
this.start_picker.setCurrentDate(new Date(start_date), true);
this.end_picker.setCurrentDate(new Date(end_date), true);
this.updateDate(is_empty);
};
//创建日期段容器
DateRangePicker.prototype.createCalendarWrap = function() {
var $parent=this.opts.ele.parents(".ui-datepicker");
var h=$parent.height()+5,w=$parent.width();
var wrap = '<div class="ui-daterangepicker-wrap pos-'+this.opts.pos+'" style="top:'+h+'px;"><div class="ui-calendar"><p class="calendar-title">开始日期</p><div class="calendar-container"></div></div>' +
'<div class="ui-calendar"><p class="calendar-title">结束日期</p><div class="calendar-container2"></div></div>' +
'<div class="ui-daterangepicker-range"><ul>' +
'<li range-key="今日">今日</li>' +
'<li range-key="昨日">昨日</li>' +
'<li range-key="最近7日">最近7日</li>' +
'<li range-key="最近30日">最近30日</li>' +
'</ul>' +
'<span class="range-btn range-confirmBtn">确定</span><span class="range-btn range-cancel">取消</span>'
'</div></div>';
$parent.append(wrap);
};

HTML:

<div class="ui-datepicker">
        <input type="text" id="daterange" placeholder="请选择日期"/>
</div>

CSS

* {
    margin: 0;
    padding: 0;
}
body{font:14px "微软雅黑";}
li {
    list-style: none;
}
.ui-datepicker{
    display: inline-block;
    position: relative;
}
.ui-calendar {
    margin: 10px;
    width: 260px;
}
.single-calendar{
    border:1px solid #ccc;
    text-align: center;
    box-shadow: 0 0 3px rgba(0,0,0,0.25);
}

.ui-calendar select {
    padding: 3px 10px;
    margin: 0 10px;
}

.calendar_header {
    margin: 10px 0;
    text-align: center;
}

.calendar-table {
    border-collapse: collapse;
}

.calendar-table td {
    padding: 5px 10px;
    cursor: pointer;
    text-align: center;
    border-radius:3px;
}
.calendar-table td.today {
    color: #337ab7;
}

.calendar-table td.active {
    background: #337ab7;
    color:#fff;
}

.calendar-table td.disabled {
    color: #ccc;
    cursor: default;
}
.ui-calendar .next-btn,
.ui-calendar .prev-btn {
    padding:1px 4px;
    border:1px solid transparent;
    border-radius:3px;
    font-weight: bold;
    cursor: pointer;
}
.ui-calendar .next-btn:hover,.ui-calendar .prev-btn:hover{
    border-color:#ccc;
    box-shadow: 0 0 3px rgba(0,0,0,0.25);
}
.ui-daterangepicker-wrap {
    position: absolute;
    top:0;
    width: 740px;
    border: 1px solid #ccc;
    border-radius:3px;
    box-shadow: 0 0 3px rgba(0,0,0,0.25);
    background: #fff;
    overflow: hidden;
    z-index:1000;
    display: none;
}
.calendar-title{
    text-align: center;
}
.ui-daterangepicker-wrap .ui-calendar {
    float: left;
}

.ui-daterangepicker-range{
    width: 150px;
    float: right;
    margin: 10px;
}
.ui-daterangepicker-range ul{
    margin-bottom:20px;
}
.ui-daterangepicker-range li {
    margin:5px 0;
    padding: 5px 10px;
    border-radius:3px;
    background: #f5f5f5;
    cursor: pointer;
}

.ui-daterangepicker-range li:hover,.ui-daterangepicker-range li.active {
    background: #337ab7;
    color:#fff;
}
.ui-daterangepicker-range .range-btn{
    width:60px;
    height: 30px;
    margin-right: 10px;
    border:1px solid #e5e5e5;
    border-radius:3px;
    background: none;
    cursor: pointer;
}
.ui-daterangepicker-range .range-confirm{
    background: #337ab7;
    border-color:#337ab7;
    color:#fff;
}

 

本文由金沙棋牌发布于金沙棋牌官方平台,转载请注明出处:Firefox的日历控件,编写一个符合国情的日期插件

关键词:

上一篇:详解及奇技淫巧

下一篇:没有了