-
Notifications
You must be signed in to change notification settings - Fork 5
/
laydate.js
1989 lines (1769 loc) · 61.1 KB
/
laydate.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
@Name : layDate 5.0.9 日期时间控件
@Author: 贤心
@Site:http://www.layui.com/laydate/
@License:MIT
*/
;!function(){
"use strict";
var isLayui = window.layui && layui.define, ready = {
getPath: function(){
var jsPath = document.currentScript ? document.currentScript.src : function(){
var js = document.scripts
,last = js.length - 1
,src;
for(var i = last; i > 0; i--){
if(js[i].readyState === 'interactive'){
src = js[i].src;
break;
}
}
return src || js[last].src;
}();
return jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
}()
//获取节点的style属性值
,getStyle: function(node, name){
var style = node.currentStyle ? node.currentStyle : window.getComputedStyle(node, null);
return style[style.getPropertyValue ? 'getPropertyValue' : 'getAttribute'](name);
}
//载入CSS配件
,link: function(href, fn, cssname){
//未设置路径,则不主动加载css
if(!laydate.path) return;
var head = document.getElementsByTagName("head")[0], link = document.createElement('link');
if(typeof fn === 'string') cssname = fn;
var app = (cssname || href).replace(/\.|\//g, '');
var id = 'layuicss-'+ app, timeout = 0;
link.rel = 'stylesheet';
link.href = laydate.path + href;
link.id = id;
if(!document.getElementById(id)){
head.appendChild(link);
}
if(typeof fn !== 'function') return;
//轮询css是否加载完毕
(function poll() {
if(++timeout > 8 * 1000 / 100){
return window.console && console.error('laydate.css: Invalid');
};
parseInt(ready.getStyle(document.getElementById(id), 'width')) === 1989 ? fn() : setTimeout(poll, 100);
}());
}
}
,laydate = {
v: '5.0.9'
,config: {} //全局配置项
,index: (window.laydate && window.laydate.v) ? 100000 : 0
,path: ready.getPath
//设置全局项
,set: function(options){
var that = this;
that.config = lay.extend({}, that.config, options);
return that;
}
//主体CSS等待事件
,ready: function(fn){
var cssname = 'laydate', ver = ''
,path = (isLayui ? 'modules/laydate/' : 'theme/') + 'default/laydate.css?v='+ laydate.v + ver;
isLayui ? layui.addcss(path, fn, cssname) : ready.link(path, fn, cssname);
return this;
}
}
//操作当前实例
,thisDate = function(){
var that = this;
return {
//提示框
hint: function(content){
that.hint.call(that, content);
}
,config: that.config
};
}
//字符常量
,MOD_NAME = 'laydate', ELEM = '.layui-laydate', THIS = 'layui-this', SHOW = 'layui-show', HIDE = 'layui-hide', DISABLED = 'laydate-disabled', TIPS_OUT = '开始日期超出了结束日期<br>建议重新选择', LIMIT_YEAR = [100, 200000]
,ELEM_STATIC = 'layui-laydate-static', ELEM_LIST = 'layui-laydate-list', ELEM_SELECTED = 'laydate-selected', ELEM_HINT = 'layui-laydate-hint', ELEM_PREV = 'laydate-day-prev', ELEM_NEXT = 'laydate-day-next', ELEM_FOOTER = 'layui-laydate-footer', ELEM_CONFIRM = '.laydate-btns-confirm', ELEM_TIME_TEXT = 'laydate-time-text', ELEM_TIME_BTN = '.laydate-btns-time'
//组件构造器
,Class = function(options){
var that = this;
that.index = ++laydate.index;
that.config = lay.extend({}, that.config, laydate.config, options);
laydate.ready(function(){
that.init();
});
}
//DOM查找
,lay = function(selector){
return new LAY(selector);
}
//DOM构造器
,LAY = function(selector){
var index = 0
,nativeDOM = typeof selector === 'object' ? [selector] : (
this.selector = selector
,document.querySelectorAll(selector || null)
);
for(; index < nativeDOM.length; index++){
this.push(nativeDOM[index]);
}
};
/*
lay对象操作
*/
LAY.prototype = [];
LAY.prototype.constructor = LAY;
//普通对象深度扩展
lay.extend = function(){
var ai = 1, args = arguments
,clone = function(target, obj){
target = target || (obj.constructor === Array ? [] : {});
for(var i in obj){
//如果值为对象,则进入递归,继续深度合并
target[i] = (obj[i] && (obj[i].constructor === Object))
? clone(target[i], obj[i])
: obj[i];
}
return target;
}
args[0] = typeof args[0] === 'object' ? args[0] : {};
for(; ai < args.length; ai++){
if(typeof args[ai] === 'object'){
clone(args[0], args[ai])
}
}
return args[0];
};
//ie版本
lay.ie = function(){
var agent = navigator.userAgent.toLowerCase();
return (!!window.ActiveXObject || "ActiveXObject" in window) ? (
(agent.match(/msie\s(\d+)/) || [])[1] || '11' //由于ie11并没有msie的标识
) : false;
}();
//中止冒泡
lay.stope = function(e){
e = e || window.event;
e.stopPropagation
? e.stopPropagation()
: e.cancelBubble = true;
};
//对象遍历
lay.each = function(obj, fn){
var key
,that = this;
if(typeof fn !== 'function') return that;
obj = obj || [];
if(obj.constructor === Object){
for(key in obj){
if(fn.call(obj[key], key, obj[key])) break;
}
} else {
for(key = 0; key < obj.length; key++){
if(fn.call(obj[key], key, obj[key])) break;
}
}
return that;
};
//数字前置补零
lay.digit = function(num, length, end){
var str = '';
num = String(num);
length = length || 2;
for(var i = num.length; i < length; i++){
str += '0';
}
return num < Math.pow(10, length) ? str + (num|0) : num;
};
//创建元素
lay.elem = function(elemName, attr){
var elem = document.createElement(elemName);
lay.each(attr || {}, function(key, value){
elem.setAttribute(key, value);
});
return elem;
};
//追加字符
LAY.addStr = function(str, new_str){
str = str.replace(/\s+/, ' ');
new_str = new_str.replace(/\s+/, ' ').split(' ');
lay.each(new_str, function(ii, item){
if(!new RegExp('\\b'+ item + '\\b').test(str)){
str = str + ' ' + item;
}
});
return str.replace(/^\s|\s$/, '');
};
//移除值
LAY.removeStr = function(str, new_str){
str = str.replace(/\s+/, ' ');
new_str = new_str.replace(/\s+/, ' ').split(' ');
lay.each(new_str, function(ii, item){
var exp = new RegExp('\\b'+ item + '\\b')
if(exp.test(str)){
str = str.replace(exp, '');
}
});
return str.replace(/\s+/, ' ').replace(/^\s|\s$/, '');
};
//查找子元素
LAY.prototype.find = function(selector){
var that = this;
var index = 0, arr = []
,isObject = typeof selector === 'object';
this.each(function(i, item){
var nativeDOM = isObject ? [selector] : item.querySelectorAll(selector || null);
for(; index < nativeDOM.length; index++){
arr.push(nativeDOM[index]);
}
that.shift();
});
if(!isObject){
that.selector = (that.selector ? that.selector + ' ' : '') + selector
}
lay.each(arr, function(i, item){
that.push(item);
});
return that;
};
//DOM遍历
LAY.prototype.each = function(fn){
return lay.each.call(this, this, fn);
};
//添加css类
LAY.prototype.addClass = function(className, type){
return this.each(function(index, item){
item.className = LAY[type ? 'removeStr' : 'addStr'](item.className, className)
});
};
//移除css类
LAY.prototype.removeClass = function(className){
return this.addClass(className, true);
};
//是否包含css类
LAY.prototype.hasClass = function(className){
var has = false;
this.each(function(index, item){
if(new RegExp('\\b'+ className +'\\b').test(item.className)){
has = true;
}
});
return has;
};
//添加或获取属性
LAY.prototype.attr = function(key, value){
var that = this;
return value === undefined ? function(){
if(that.length > 0) return that[0].getAttribute(key);
}() : that.each(function(index, item){
item.setAttribute(key, value);
});
};
//移除属性
LAY.prototype.removeAttr = function(key){
return this.each(function(index, item){
item.removeAttribute(key);
});
};
//设置HTML内容
LAY.prototype.html = function(html){
return this.each(function(index, item){
item.innerHTML = html;
});
};
//设置值
LAY.prototype.val = function(value){
return this.each(function(index, item){
item.value = value;
});
};
//追加内容
LAY.prototype.append = function(elem){
return this.each(function(index, item){
typeof elem === 'object'
? item.appendChild(elem)
: item.innerHTML = item.innerHTML + elem;
});
};
//移除内容
LAY.prototype.remove = function(elem){
return this.each(function(index, item){
elem ? item.removeChild(elem) : item.parentNode.removeChild(item);
});
};
//事件绑定
LAY.prototype.on = function(eventName, fn){
return this.each(function(index, item){
item.attachEvent ? item.attachEvent('on' + eventName, function(e){
e.target = e.srcElement;
fn.call(item, e);
}) : item.addEventListener(eventName, fn, false);
});
};
//解除事件
LAY.prototype.off = function(eventName, fn){
return this.each(function(index, item){
item.detachEvent
? item.detachEvent('on'+ eventName, fn)
: item.removeEventListener(eventName, fn, false);
});
};
/*
组件操作
*/
//是否闰年
Class.isLeapYear = function(year){
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
};
//默认配置
Class.prototype.config = {
type: 'date' //控件类型,支持:year/month/date/time/datetime
,range: false //是否开启范围选择,即双控件
,format: 'yyyy-MM-dd' //默认日期格式
,value: null //默认日期,支持传入new Date(),或者符合format参数设定的日期格式字符
,min: '1900-1-1' //有效最小日期,年月日必须用“-”分割,时分秒必须用“:”分割。注意:它并不是遵循 format 设定的格式。
,max: '2099-12-31' //有效最大日期,同上
,trigger: 'focus' //呼出控件的事件
,show: false //是否直接显示,如果设置true,则默认直接显示控件
,showBottom: true //是否显示底部栏
,btns: ['clear', 'now', 'confirm'] //右下角显示的按钮,会按照数组顺序排列
,lang: 'cn' //语言,只支持cn/en,即中文和英文
,theme: 'default' //主题
,position: null //控件定位方式定位, 默认absolute,支持:fixed/absolute/static
,calendar: false //是否开启公历重要节日,仅支持中文版
,mark: {} //日期备注,如重要事件或活动标记
,zIndex: null //控件层叠顺序
,done: null //控件选择完毕后的回调,点击清空/现在/确定也均会触发
,change: null //日期时间改变后的回调
};
//多语言
Class.prototype.lang = function(){
var that = this
,options = that.config
,text = {
cn: {
weeks: ['日', '一', '二', '三', '四', '五', '六']
,time: ['时', '分', '秒']
,timeTips: '选择时间'
,startTime: '开始时间'
,endTime: '结束时间'
,dateTips: '返回日期'
,month: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二']
,tools: {
confirm: '确定'
,clear: '清空'
,now: '现在'
}
}
,en: {
weeks: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
,time: ['Hours', 'Minutes', 'Seconds']
,timeTips: 'Select Time'
,startTime: 'Start Time'
,endTime: 'End Time'
,dateTips: 'Select Date'
,month: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
,tools: {
confirm: 'Confirm'
,clear: 'Clear'
,now: 'Now'
}
}
};
return text[options.lang] || text['cn'];
};
//初始准备
Class.prototype.init = function(){
var that = this
,options = that.config
,dateType = 'yyyy|y|MM|M|dd|d|HH|H|mm|m|ss|s'
,isStatic = options.position === 'static'
,format = {
year: 'yyyy'
,month: 'yyyy-MM'
,date: 'yyyy-MM-dd'
,time: 'HH:mm:ss'
,datetime: 'yyyy-MM-dd HH:mm:ss'
};
options.elem = lay(options.elem);
options.eventElem = lay(options.eventElem);
if(!options.elem[0]) return;
//日期范围分隔符
if(options.range === true) options.range = '-';
//根据不同type,初始化默认format
if(options.format === format.date){
options.format = format[options.type];
}
//将日期格式转化成数组
that.format = options.format.match(new RegExp(dateType + '|.', 'g')) || [];
//生成正则表达式
that.EXP_IF = '';
that.EXP_SPLIT = '';
lay.each(that.format, function(i, item){
var EXP = new RegExp(dateType).test(item)
? '\\d{'+ function(){
if(new RegExp(dateType).test(that.format[i === 0 ? i + 1 : i - 1]||'')){
if(/^yyyy|y$/.test(item)) return 4;
return item.length;
}
if(/^yyyy$/.test(item)) return '1,4';
if(/^y$/.test(item)) return '1,308';
return '1,2';
}() +'}'
: '\\' + item;
that.EXP_IF = that.EXP_IF + EXP;
that.EXP_SPLIT = that.EXP_SPLIT + '(' + EXP + ')';
});
that.EXP_IF = new RegExp('^'+ (
options.range ?
that.EXP_IF + '\\s\\'+ options.range + '\\s' + that.EXP_IF
: that.EXP_IF
) +'$');
that.EXP_SPLIT = new RegExp('^'+ that.EXP_SPLIT +'$', '');
//如果不是input|textarea元素,则默认采用click事件
if(!that.isInput(options.elem[0])){
if(options.trigger === 'focus'){
options.trigger = 'click';
}
}
//设置唯一KEY
if(!options.elem.attr('lay-key')){
options.elem.attr('lay-key', that.index);
options.eventElem.attr('lay-key', that.index);
}
//记录重要日期
options.mark = lay.extend({}, (options.calendar && options.lang === 'cn') ? {
'0-1-1': '元旦'
,'0-2-14': '情人'
,'0-3-8': '妇女'
,'0-3-12': '植树'
,'0-4-1': '愚人'
,'0-5-1': '劳动'
,'0-5-4': '青年'
,'0-6-1': '儿童'
,'0-9-10': '教师'
,'0-9-18': '国耻'
,'0-10-1': '国庆'
,'0-12-25': '圣诞'
} : {}, options.mark);
//获取限制内日期
lay.each(['min', 'max'], function(i, item){
var ymd = [], hms = [];
if(typeof options[item] === 'number'){ //如果为数字
var day = options[item]
,time = new Date().getTime()
,STAMP = 86400000 //代表一天的时间戳
,thisDate = new Date(
day ? (
day < STAMP ? time + day*STAMP : day //如果数字小于一天的时间戳,则数字为天数,否则为时间戳
) : time
);
ymd = [thisDate.getFullYear(), thisDate.getMonth() + 1, thisDate.getDate()];
day < STAMP || (hms = [thisDate.getHours(), thisDate.getMinutes(), thisDate.getSeconds()]);
} else {
ymd = (options[item].match(/\d+-\d+-\d+/) || [''])[0].split('-');
hms = (options[item].match(/\d+:\d+:\d+/) || [''])[0].split(':');
}
options[item] = {
year: ymd[0] | 0 || new Date().getFullYear()
,month: ymd[1] ? (ymd[1] | 0) - 1 : new Date().getMonth()
,date: ymd[2] | 0 || new Date().getDate()
,hours: hms[0] | 0
,minutes: hms[1] | 0
,seconds: hms[2] | 0
};
});
that.elemID = 'layui-laydate'+ options.elem.attr('lay-key');
if(options.show || isStatic) that.render();
isStatic || that.events();
//默认赋值
if(options.value){
if(options.value.constructor === Date){
that.setValue(that.parse(0, that.systemDate(options.value)));
} else {
that.setValue(options.value);
}
}
};
//控件主体渲染
Class.prototype.render = function(){
var that = this
,options = that.config
,lang = that.lang()
,isStatic = options.position === 'static'
//主面板
,elem = that.elem = lay.elem('div', {
id: that.elemID
,'class': [
'layui-laydate'
,options.range ? ' layui-laydate-range' : ''
,isStatic ? (' '+ ELEM_STATIC) : ''
,options.theme && options.theme !== 'default' && !/^#/.test(options.theme) ? (' laydate-theme-' + options.theme) : ''
].join('')
})
//扩展-顶部区域快捷选择
,divTop = that.top = lay.elem('div', {
'class': 'layui-laydate-top'
})
//主区域
,elemMain = that.elemMain = []
,elemHeader = that.elemHeader = []
,elemCont = that.elemCont = []
,elemTable = that.table = []
//底部区域
,divFooter = that.footer = lay.elem('div', {
'class': ELEM_FOOTER
});
if(options.zIndex) elem.style.zIndex = options.zIndex;
//单双日历区域
lay.each(new Array(2), function(i){
if(!options.range && i > 0){
return true;
}
//头部区域
var divHeader = lay.elem('div', {
'class': 'layui-laydate-header'
})
//左右切换
,headerChild = [function(){ //上一年
var elem = lay.elem('i', {
'class': 'layui-icon laydate-icon laydate-prev-y'
});
elem.innerHTML = '';
return elem;
}(), function(){ //上一月
var elem = lay.elem('i', {
'class': 'layui-icon laydate-icon laydate-prev-m'
});
elem.innerHTML = '';
return elem;
}(), function(){ //年月选择
var elem = lay.elem('div', {
'class': 'laydate-set-ym'
}), spanY = lay.elem('span'), spanM = lay.elem('span');
elem.appendChild(spanY);
elem.appendChild(spanM);
return elem;
}(), function(){ //下一月
var elem = lay.elem('i', {
'class': 'layui-icon laydate-icon laydate-next-m'
});
elem.innerHTML = '';
return elem;
}(), function(){ //下一年
var elem = lay.elem('i', {
'class': 'layui-icon laydate-icon laydate-next-y'
});
elem.innerHTML = '';
return elem;
}()]
//日历内容区域
,divContent = lay.elem('div', {
'class': 'layui-laydate-content'
})
,table = lay.elem('table')
,thead = lay.elem('thead'), theadTr = lay.elem('tr');
//生成年月选择
lay.each(headerChild, function(i, item){
divHeader.appendChild(item);
});
//生成表格
thead.appendChild(theadTr);
lay.each(new Array(6), function(i){ //表体
var tr = table.insertRow(0);
lay.each(new Array(7), function(j){
if(i === 0){
var th = lay.elem('th');
th.innerHTML = lang.weeks[j];
theadTr.appendChild(th);
}
tr.insertCell(j);
});
});
table.insertBefore(thead, table.children[0]); //表头
divContent.appendChild(table);
elemMain[i] = lay.elem('div', {
'class': 'layui-laydate-main laydate-main-list-'+ i
});
elemMain[i].appendChild(divHeader);
elemMain[i].appendChild(divContent);
elemHeader.push(headerChild);
elemCont.push(divContent);
elemTable.push(table);
});
//扩展-生成顶部栏
lay(divTop).html(function(){
var html = [], btns = [];
if(options.extrabtns){
lay.each(options.extrabtns, function (e, t) {
btns.push('<span lay-type="' + t.id + '" class="laydate-btns-' + t.id + '">' + t.text + "</span>")
})
}
html.push('<div class="laydate-top-btns">快速查看:'+ btns.join('') +'</div>');
return html.join('');
}());
//生成底部栏
lay(divFooter).html(function(){
var html = [], btns = [];
if(options.type === 'datetime'){
html.push('<span lay-type="datetime" class="laydate-btns-time">'+ lang.timeTips +'</span>');
}
lay.each(options.btns, function(i, item){
var title = lang.tools[item] || 'btn';
if(options.range && item === 'now') return;
if(isStatic && item === 'clear') title = options.lang === 'cn' ? '重置' : 'Reset';
btns.push('<span lay-type="'+ item +'" class="laydate-btns-'+ item +'">'+ title +'</span>');
});
html.push('<div class="laydate-footer-btns">'+ btns.join('') +'</div>');
return html.join('');
}());
//插入到主区域
elem.appendChild(divTop);
lay.each(elemMain, function(i, main){
elem.appendChild(main);
});
options.showBottom && elem.appendChild(divFooter);
//生成自定义主题
if(/^#/.test(options.theme)){
var style = lay.elem('style')
,styleText = [
'#{{id}} .layui-laydate-header{background-color:{{theme}};}'
,'#{{id}} .layui-this{background-color:{{theme}} !important;}'
].join('').replace(/{{id}}/g, that.elemID).replace(/{{theme}}/g, options.theme);
if('styleSheet' in style){
style.setAttribute('type', 'text/css');
style.styleSheet.cssText = styleText;
} else {
style.innerHTML = styleText;
}
lay(elem).addClass('laydate-theme-molv');
elem.appendChild(style);
}
//移除上一个控件
that.remove(Class.thisElemDate);
//如果是静态定位,则插入到指定的容器中,否则,插入到body
isStatic ? options.elem.append(elem) : (
document.body.appendChild(elem)
,that.position() //定位
);
that.checkDate().calendar(); //初始校验
that.changeEvent(); //日期切换
Class.thisElemDate = that.elemID;
typeof options.ready === 'function' && options.ready(lay.extend({}, options.dateTime, {
month: options.dateTime.month + 1
}));
};
//控件移除
Class.prototype.remove = function(prev){
var that = this
,options = that.config
,elem = lay('#'+ (prev || that.elemID));
if(!elem.hasClass(ELEM_STATIC)){
that.checkDate(function(){
elem.remove();
});
}
return that;
};
//定位算法
Class.prototype.position = function(){
var that = this
,options = that.config
,elem = that.bindElem || options.elem[0]
,rect = elem.getBoundingClientRect() //绑定元素的坐标
,elemWidth = that.elem.offsetWidth //控件的宽度
,elemHeight = that.elem.offsetHeight //控件的高度
//滚动条高度
,scrollArea = function(type){
type = type ? 'scrollLeft' : 'scrollTop';
return document.body[type] | document.documentElement[type];
}
,winArea = function(type){
return document.documentElement[type ? 'clientWidth' : 'clientHeight']
}, margin = 5, left = rect.left, top = rect.bottom;
//如果右侧超出边界
if(left + elemWidth + margin > winArea('width')){
left = winArea('width') - elemWidth - margin;
}
//如果底部超出边界
if(top + elemHeight + margin > winArea()){
top = rect.top > elemHeight //顶部是否有足够区域显示完全
? rect.top - elemHeight
: winArea() - elemHeight;
top = top - margin*2;
}
if(options.position){
that.elem.style.position = options.position;
}
that.elem.style.left = left + (options.position === 'fixed' ? 0 : scrollArea(1)) + 'px';
that.elem.style.top = top + (options.position === 'fixed' ? 0 : scrollArea()) + 'px';
};
//提示
Class.prototype.hint = function(content){
var that = this
,options = that.config
,div = lay.elem('div', {
'class': ELEM_HINT
});
div.innerHTML = content || '';
lay(that.elem).find('.'+ ELEM_HINT).remove();
that.elem.appendChild(div);
clearTimeout(that.hinTimer);
that.hinTimer = setTimeout(function(){
lay(that.elem).find('.'+ ELEM_HINT).remove();
}, 3000);
};
//获取递增/减后的年月
Class.prototype.getAsYM = function(Y, M, type){
type ? M-- : M++;
if(M < 0){
M = 11;
Y--;
}
if(M > 11){
M = 0;
Y++;
}
return [Y, M];
};
//系统消息
Class.prototype.systemDate = function(newDate){
var thisDate = newDate || new Date();
return {
year: thisDate.getFullYear() //年
,month: thisDate.getMonth() //月
,date: thisDate.getDate() //日
,hours: newDate ? newDate.getHours() : 0 //时
,minutes: newDate ? newDate.getMinutes() : 0 //分
,seconds: newDate ? newDate.getSeconds() : 0 //秒
}
};
//日期校验
Class.prototype.checkDate = function(fn){
var that = this
,thisDate = new Date()
,options = that.config
,dateTime = options.dateTime = options.dateTime || that.systemDate()
,thisMaxDate, error
,elem = that.bindElem || options.elem[0]
,valType = that.isInput(elem) ? 'val' : 'html'
,value = that.isInput(elem) ? elem.value : (options.position === 'static' ? '' : elem.innerHTML)
//校验日期有效数字
,checkValid = function(dateTime){
if(dateTime.year > LIMIT_YEAR[1]) dateTime.year = LIMIT_YEAR[1], error = true; //不能超过20万年
if(dateTime.month > 11) dateTime.month = 11, error = true;
if(dateTime.hours > 23) dateTime.hours = 0, error = true;
if(dateTime.minutes > 59) dateTime.minutes = 0, dateTime.hours++, error = true;
if(dateTime.seconds > 59) dateTime.seconds = 0, dateTime.minutes++, error = true;
//计算当前月的最后一天
thisMaxDate = laydate.getEndDate(dateTime.month + 1, dateTime.year);
if(dateTime.date > thisMaxDate) dateTime.date = thisMaxDate, error = true;
}
//获得初始化日期值
,initDate = function(dateTime, value, index){
var startEnd = ['startTime', 'endTime'];
value = (value.match(that.EXP_SPLIT) || []).slice(1);
index = index || 0;
if(options.range){
that[startEnd[index]] = that[startEnd[index]] || {};
}
lay.each(that.format, function(i, item){
var thisv = parseFloat(value[i]);
if(value[i].length < item.length) error = true;
if(/yyyy|y/.test(item)){ //年
if(thisv < LIMIT_YEAR[0]) thisv = LIMIT_YEAR[0], error = true; //年不能低于100年
dateTime.year = thisv;
} else if(/MM|M/.test(item)){ //月
if(thisv < 1) thisv = 1, error = true;
dateTime.month = thisv - 1;
} else if(/dd|d/.test(item)){ //日
if(thisv < 1) thisv = 1, error = true;
dateTime.date = thisv;
} else if(/HH|H/.test(item)){ //时
if(thisv < 1) thisv = 0, error = true;
dateTime.hours = thisv;
options.range && (that[startEnd[index]].hours = thisv);
} else if(/mm|m/.test(item)){ //分
if(thisv < 1) thisv = 0, error = true;
dateTime.minutes = thisv;
options.range && (that[startEnd[index]].minutes = thisv);
} else if(/ss|s/.test(item)){ //秒
if(thisv < 1) thisv = 0, error = true;
dateTime.seconds = thisv;
options.range && (that[startEnd[index]].seconds = thisv);
}
});
checkValid(dateTime)
};
if(fn === 'limit') return checkValid(dateTime), that;
value = value || options.value;
if(typeof value === 'string'){
value = value.replace(/\s+/g, ' ').replace(/^\s|\s$/g, '');
}
//如果点击了开始,单未选择结束就关闭,则重新选择开始
if(that.startState && !that.endState){
delete that.startState;
that.endState = true;
};
if(typeof value === 'string' && value){
if(that.EXP_IF.test(value)){ //校验日期格式
if(options.range){
value = value.split(' '+ options.range +' ');
that.startDate = that.startDate || that.systemDate();
that.endDate = that.endDate || that.systemDate();
options.dateTime = lay.extend({}, that.startDate);
lay.each([that.startDate, that.endDate], function(i, item){
initDate(item, value[i], i);
});
} else {
initDate(dateTime, value)
}
} else {
that.hint('日期格式不合法<br>必须遵循下述格式:<br>'+ (
options.range ? (options.format + ' '+ options.range +' ' + options.format) : options.format
) + '<br>已为你重置');
error = true;
}
} else if(value && value.constructor === Date){ //如果值为日期对象时
options.dateTime = that.systemDate(value);
} else {
options.dateTime = that.systemDate();
delete that.startState;
delete that.endState;
delete that.startDate;
delete that.endDate;
delete that.startTime;
delete that.endTime;
}
checkValid(dateTime);
if(error && value){
that.setValue(
options.range ? (that.endDate ? that.parse() : '') : that.parse()
);
}
fn && fn();
return that;
};
//公历重要日期与自定义备注
Class.prototype.mark = function(td, YMD){
var that = this
,mark, options = that.config;
lay.each(options.mark, function(key, title){
var keys = key.split('-');
if((keys[0] == YMD[0] || keys[0] == 0) //每年的每月
&& (keys[1] == YMD[1] || keys[1] == 0) //每月的每日
&& keys[2] == YMD[2]){ //特定日
mark = title || YMD[2];
}
});
mark && td.html('<span class="laydate-day-mark">'+ mark +'</span>');
return that;
};
//无效日期范围的标记
Class.prototype.limit = function(elem, date, index, time){
var that = this
,options = that.config, timestrap = {}
,dateTime = options[index > 41 ? 'endDate' : 'dateTime']
,isOut, thisDateTime = lay.extend({}, dateTime, date || {});
lay.each({
now: thisDateTime
,min: options.min
,max: options.max
}, function(key, item){
timestrap[key] = that.newDate(lay.extend({
year: item.year
,month: item.month
,date: item.date
}, function(){
var hms = {};
lay.each(time, function(i, keys){
hms[keys] = item[keys];
});
return hms;
}())).getTime(); //time:是否比较时分秒