JavaScript实现日期选择器

[ JavaScript ] 2019-12-19 21:55:02 杨歆 496
var eLuoDate = {

    el: '.date',

    show: '.show',

    ymd: null,

    selected: [],

    callback: function(){},
    version: 'v1.1008.1351',

    init(object){

        let _this = this;
        this.el = object.el ? object.el : this.el;
        this.show = object.show ? object.show: this.show;
        this.ymd = (function(){
            let date = _this.date(),
                currentDateArray = [];
            currentDateArray.push(date.year);
            currentDateArray.push(date.month);
            currentDateArray.push((date.day < 10) ? '0' + date.day : date.day);
            return currentDateArray.join('-');
        })();
        this.selected = (function(selected){

            let selectedArray = [];
            if(typeof selected == "function"){
                selectedArray = selected(_this);
            }
            if(Array.isArray(selected)){
                selectedArray = selected;
            }

            return selectedArray;

        })(object.selected);


        this.callback = object.callback ? object.callback: this.callback;

        let showFunction = function(show, selected){
            if(show){
                let showEl = document.querySelector(show);
                if(showEl instanceof HTMLElement){
                    showEl.innerHTML = '';
                    if(selected.length > 0){
                        selected.sort();
                        for(let i=0,len=selected.length; i<len; i++){
                            let strong = document.createElement('strong'),
                                stylesheet = {
                                    border: '1px solid #090',
                                    borderRadius: '5px',
                                    display: 'inline-block',
                                    background: '#fcfcfc',
                                    padding: '2px 10px',
                                    margin: '0 10px 10px 0',
                                    color: '#090',
                                    fontSize: '15px',
                                };
                            for(key in stylesheet){
                                strong.style[key] = stylesheet[key];
                            }
                            strong.innerText = selected[i];
                            let five = document.createElement('input');
                            five.setAttribute('type', 'hidden');
                            five.setAttribute('name', 'fives[]');
                            five.value = selected[i];
                            strong.appendChild(five);
                            showEl.appendChild(strong);
                        };
                    }else{
                        showEl.innerHTML = showEl.dataset.msg ? showEl.dataset.msg : '选择日期';
                    }
                }
            }
        };

        if(typeof this.show == 'function'){
            this.show(this.selected);
        }else{
            showFunction(this.show, this.selected);
        }

        let eventFunction, leftCallBack, rightCallBack, todayCallBack;
        eventFunction = function(item){
            let year = item.dataset.year,
                month = item.dataset.month,
                date = item.dataset.date;
            let ymdArray = [];
            ymdArray.push(year);
            ymdArray.push(month < 10 ? '0' + month : month);
            ymdArray.push(date < 10 ? '0' + date : date);
            let ymd = ymdArray.join('-');
            let index = _this.selected.indexOf(parseInt(date));
            if(index == -1){
                _this.selected.push(parseInt(date));
            }else{
                _this.selected.splice(index, 1);
            }
            if(typeof _this.callback == 'function'){
                _this.callback(_this.selected);
            };
            _this.create(ymd, eventFunction, leftCallBack, rightCallBack, todayCallBack);
            showFunction(_this.show, _this.selected);

        };

        leftCallBack = function(date, type, left){
            let year = type == 'year' ? date.year - 1 : date.year,
                month = type == 'month' ? (date.month - 1 == 0 ? 1 : date.month - 1) : date.month;
            let ymd = [year, month, date.date].join('-');
            _this.create(ymd, eventFunction, leftCallBack, rightCallBack, todayCallBack);

        }

        rightCallBack = function(date, type, right){
            let year = type == 'year' ? date.year + 1 : date.year,
                month = type == 'month' ? (date.month + 1 >= 12 ? 12 : date.month + 1) : date.month;
            let ymd = [year, month, date.date].join('-');
            _this.create(ymd, eventFunction, leftCallBack, rightCallBack, todayCallBack);
        }

        todayCallBack = function(today){
            _this.create(null, eventFunction, leftCallBack, rightCallBack, todayCallBack);
        }

        this.create(this.ymd, eventFunction, leftCallBack, rightCallBack, todayCallBack);
        return this;
    },

    create(ymd, callback, leftCallBack, rightCallBack, todayCallBack){
        let _this = this,
            date = this.date(ymd),
            el = document.querySelector(this.el),
            lrFunc = function(innerText, leftCallBack, rightCallBack, type){
                let div = document.createElement('div');
                div.style.display = 'inline-block';
                div.style.margin = '0 10px';
                let left = document.createElement('span');
                left.innerText = '<';
                left.style.fontWeight = 'bold';
                left.style.padding = '0 5px';
                left.style.cursor = 'pointer';
                left.style.background = '#09f';
                left.style.color = '#fff';
                left.style.display = 'inline-block';
                left.style.lineHeight = '24px';
                left.style.borderRadius = '5px';
                left.addEventListener('click', function(){leftCallBack(date, type, this);});
                div.appendChild(left);
                let span = document.createElement('span');
                span.innerText = innerText;
                span.style.fontWeight = 'bold';
                span.style.fontSize = '20px';
                span.style.padding = '0 10px';
                span.style.display = 'inline-block';
                span.style.lineHeight = '24px';
                span.style.position = 'relative';
                span.style.top = '0px';
                div.appendChild(span);
                let right = document.createElement('span');
                right.innerText = '>';
                right.style.fontWeight = 'bold';
                right.style.padding = '0 5px';
                right.style.cursor = 'pointer';
                right.style.background = '#09f';
                right.style.lineHeight = '24px';
                right.style.color = '#fff';
                right.style.display = 'inline-block';
                right.style.borderRadius = '5px';
                right.addEventListener('click', function(){rightCallBack(date, type, this);});
                div.appendChild(right);
                return div;
            };
        el.style.userSelect = 'none';
        // 顶部
        let top = document.createElement('div');
        top.setAttribute('class', 'date-top');
        top.style.marginBottom = '-1px';
        top.style.padding = '10px 0';
        top.style.textAlign = 'center';
        top.style.background = '#eee';
        // 年
        top.appendChild(lrFunc(date.year, leftCallBack, rightCallBack, 'year'));
        // 月
        let innerText = (date.month < 10) ? '0' + date.month : date.month;
        top.appendChild(lrFunc(innerText, leftCallBack, rightCallBack, 'month'));
        // 返回今天
        top.appendChild((function(todayCallBack){
            let div = document.createElement('div');
            div.innerText = '返回今天';
            div.style.display = 'inline-block';
            div.style.background = '#e64340';
            div.style.padding = '0 10px';
            div.style.color = '#fff';
            div.style.cursor = 'pointer';
            div.style.lineHeight = '24px';
            div.style.position = 'relative';
            div.style.top = '3px';
            div.style.borderRadius = '5px';
            div.addEventListener('click', function(){
                todayCallBack(this);
            });
            return div;
        })(todayCallBack));
        if(el.querySelector('.date-top') instanceof HTMLElement){
            el.removeChild(el.querySelector('.date-top'));
        }
        el.appendChild(top);
        // 星期
        if(el.querySelector('.date-week') instanceof HTMLElement){
            el.removeChild(el.querySelector('.date-week'));
        }
        el.appendChild((function(){
            let weekZhArray = ['日', '一', '二', '三', '四', '五', '六'],
                weekZhArrayLength = weekZhArray.length,
                week = document.createElement('div');
            week.setAttribute('class', 'date-week');
            week.style.paddingLeft = '0.6%';
            for(let i=0; i<weekZhArrayLength; i++){
                let div = document.createElement('div');
                div.innerText = weekZhArray[i];
                div.style.width = '14%';
                div.style.float = 'left';
                div.style.margin = '0 -1px -1px 0';
                div.style.padding = '20px 0';
                div.style.textAlign = 'center';
                div.style.fontWeight = 'bold';
                div.style.fontSize = '16px';
                div.style.border = '1px solid transparent';
                week.appendChild(div);
            }
            week.appendChild((function(){
                let span = document.createElement('span');
                span.style.display = 'block';
                span.style.clear = 'both';
                return span;
            })());
            return week;
        })());

        let count = 42;
        let ulDiv = document.createElement('div');
        let ymdStringFunction = function(ymd, idx){
            let ymdArray = new Array();
            ymdArray.push(ymd.year);
            ymdArray.push(ymd.month < 10 ? '0' + ymd.month : ymd.month);
            ymdArray.push(idx < 10 ? '0' + idx : idx);
            return ymdArray.join('-');
        };
        ulDiv.setAttribute('class', 'date-list');
        ulDiv.style.paddingLeft = '0.6%';
        // 当月1号之前
        let i = date.prev.date - (date.first.day == 0 ? 7 : date.first.day) + 1;
        for( ; i<=date.prev.date; i++){
            let li = document.createElement('div');
            li.setAttribute('data-year', date.prev.year);
            li.setAttribute('data-month', date.prev.month);
            li.setAttribute('data-date', i);
            li.setAttribute('data-ymd', ymdStringFunction(date.prev, i));
            li.innerText = i;
            let styles = {
                float: 'left',
                listStyle: 'none',
                border: '1px solid #eee',
                width: '14%',
                margin: '0 -1px -1px 0',
                textAlign: 'center',
                padding: '10px 0',
                color: '#888',
                cursor: 'pointer',
                position: 'relative',
                zIndex: 0
            };

            for(style in styles){
                li.style[style] = styles[style];
            }

            li.onclick = function(){
                callback(this);
            };
            ulDiv.appendChild(li);
            count--;
        }
        // 当月
        for(let i=1; i<=date.last.date; i++){
            let li = document.createElement('div');
            li.setAttribute('data-year', date.year);
            li.setAttribute('data-month', date.month);
            li.setAttribute('data-date', i);
            li.setAttribute('data-ymd', ymdStringFunction(date, i));
            li.innerText = i;
            let styles = {
                float: 'left',
                listStyle: 'none',
                border: '1px solid #eee',
                width: '14%',
                margin: '0 -1px -1px 0',
                textAlign: 'center',
                padding: '10px 0',
                fontWeight: 'bold',
                color: '#09f',
                background: '#fcfcfc',
                cursor: 'pointer',
                position: 'relative',
                zIndex: 0
            };

            let selectedIcon = function(){
                let iIcon = document.createElement('i'),
                    stylesheet = {
                        border: '4px solid #090',
                        borderTop: 'none',
                        borderLeft: 'none',
                        display: 'block',
                        position: 'absolute',
                        right: '10px',
                        bottom: '10px',
                        width: '5px',
                        height: '10px',
                        transform: 'rotate(45deg)'
                    };
                for(style in stylesheet){
                    iIcon.style[style] = stylesheet[style];
                }
                return iIcon;
            };
            //let arrayIndex = _this.selected.indexOf(ymdStringFunction(date, i));
            let arrayIndex = _this.selected.indexOf(i);
            if(arrayIndex != -1){
                li.appendChild(selectedIcon());
            }
            if(i == date.date){
                styles.background = 'rgba(0, 153, 255, .2)';
            }
            for(style in styles){
                li.style[style] = styles[style];
            }
            li.onclick = function(){
                callback(this);
            };
            ulDiv.appendChild(li);
            count--;
        }
        // 当月最后一天之后
        let nextEnd = count;
        for(let i=1; i<=nextEnd; i++){
            let li = document.createElement('div');
            li.setAttribute('data-year', date.next.year);
            li.setAttribute('data-month', date.next.month);
            li.setAttribute('data-date', i);
            li.setAttribute('data-ymd', ymdStringFunction(date.next, i));
            li.innerText = i;
            let styles = {
                float: 'left',
                listStyle: 'none',
                border: '1px solid #eee',
                width: '14%',
                margin: '0 -1px -1px 0',
                textAlign: 'center',
                padding: '10px 0',
                color: '#888',
                cursor: 'pointer'
            };
            for(style in styles){
                li.style[style] = styles[style];
            }
            li.onclick = function(){
                callback(this);
            };

            ulDiv.appendChild(li);
        }
        ulDiv.appendChild((function(){
            let span = document.createElement('span');
            span.style.display = 'block';
            span.style.clear = 'both';
            return span;
        })());
        if(el.querySelector('.date-list') instanceof HTMLElement){
            el.removeChild(el.querySelector('.date-list'));
        }

        el.appendChild(ulDiv);
    },

    date(dateTime){
        let date = new Date();
        if(dateTime){
            date = new Date(dateTime);
        }
        return {
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            date: date.getDate(),
            hours: date.getHours(),
            minutes: date.getMinutes(),
            seconds: date.getSeconds(),
            day: date.getDay(),
            first: (function(){
                let first = new Date(date.getFullYear(), date.getMonth(), 1);
                return {
                    year: first.getFullYear(),
                    month: first.getMonth() + 1,
                    date: first.getDate(),
                    day: first.getDay()
                };
            })(),
            last: (function(){
                let last = new Date(date.getFullYear(), date.getMonth() + 1, 0);
                return {
                    year: last.getFullYear(),
                    month: last.getMonth() + 1,
                    date: last.getDate(),
                    day: last.getDay()
                };
            })(),
            prev: (function(){
                let prev = new Date(date.getFullYear(), date.getMonth(), 0);
                return {
                    year: prev.getFullYear(),
                    month: prev.getMonth() + 1,
                    date: prev.getDate(),
                    day: prev.getDay()
                };
            })(),
            next: (function(){
                let next = new Date(date.getFullYear(), date.getMonth() + 2, 0);
                return {
                    year: next.getFullYear(),
                    month: next.getMonth() + 1,
                    date: next.getDate(),
                    day: next.getDay()
                };
            })(),
        };
    }

};
支付宝支付
打赏
微信支付

联系我吧

有些人是会淡出你的生活的,有些人刻意不再联系,是因为你知道ta不需要你,或者从一开始就不是同一个初衷在一起度过,不主动联系很久也不见一次面,所有的感情也罢,都会败给时间和距离。因为时间是最无情,给你后悔的时刻却不会给你改过重来的机会。

位置

成都市 四川省 中国

联系电话

028-6406-0000

邮箱

y139w@163.com

企鹅

27572048

网址

https://www.weania.com