前端jquery日期插件

分享一个前端jquery日期插件,方便自己后面需要时查找使用。

效果:

1、html demo。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>时间控件</title>
    <link rel="stylesheet" href="dateSelect.css">
    <script src="https://www.jq22.com/jquery/jquery-1.10.2.js"></script>
    <script src="mobileSelect.js"></script>
    <script src="dateSelect.js"></script>
    <style> 
		html,body{
            margin: 0;
            padding: 0;
            background-color: #ffffff;
            font-size: 16px;
            font-family: Helvetica,"Helvetica Neue",Arial,sans-serif;
            height: 100%;
        }
        *{
            margin: 0;
            padding: 0;
        }
        .list{
            margin: 50px 25px 0 25px;
            text-align: center;
        }
        .list>li{
            list-style: none;
            border: #CCCCCC solid 1px;
            height: 32px;
            line-height: 32px;
            border-radius: 5px;
            margin-bottom: 15px;
        }
		.colors{
			color: #E60012 !important;
		}
		.mobileSelect .content{
			width: 96% !important;
			border-radius: 0.3rem !important;
			bottom: 1rem !important;
			margin-left: 2% !important;
		}
		.cancel{
			color: #E60012 !important;
		}
		.title{
			color: #333 !important;
		}
		.ensure{
			color: #007AFF !important;
		}
		.selectLine{
			display: flex;
			align-items: center;
		}
		.selectLine span{
			width: 33.3%;
			height: 40px;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-bottom: 3px;
		}
    </style>
</head>
<body>
	<h3 style="line-height: 50px">点击下方输入框</h3>
    <div>
        <input type="text" id="select_0" placeholder="请选择开始时间"/> 
        <input type="text" id="select_1" placeholder="请选择结束时间"/> 
    </div>
</body>
</html>
<script>
	//选择 YYYY-MM-dd 格式的调用:
	$.selectYY_MM_DD("#select_0");
	$.selectYY_MM_DD("#select_1");
</script>

2、 dateSelect.css

.mobileSelect{
  position: relative;
  z-index: 0;
  opacity: 0;
  visibility: hidden;
  -webkit-transition: all 0.4s;
  transition: all 0.4s;
}
.mobileSelect .grayLayer {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: #eee;
  background: rgba(0, 0, 0, 0.7);
  z-index: 888;
  display: block;
}
.mobileSelect .content {
  width: 100%;
  display: block;
  position: fixed;
  z-index: 889;
  color: black;
  -webkit-transition: all 0.4s;
  transition: all 0.4s;
  bottom: -350px;
  left:0;
  background: white;
}
.mobileSelect .content .fixWidth {
  width: 90%;
  margin: 0 auto;
  position: relative;
}
.mobileSelect .content .fixWidth:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.mobileSelect .content .btnBar {
  border-bottom: 1px solid #DCDCDC;
  font-size: 15px;
  height: 45px;
  position: relative;
  text-align: center;
  line-height: 45px;
}
.mobileSelect .content .btnBar .cancel,
.mobileSelect .content .btnBar .ensure {
  height: 45px;
  width: 55px;
  cursor: pointer;
  position: absolute;
  top: 0;
}
.mobileSelect .content .btnBar .cancel {
  left: 0;
  color: #666;
}
.mobileSelect .content .btnBar .ensure {
  right: 0;
  color: #1e83d3;
}
.mobileSelect .content .btnBar .title {
  font-size: 15px;
}
.mobileSelect .content .panel:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.mobileSelect .content .panel .wheels {
  width: 100%;
  height: 200px;
  overflow: hidden;
}
.mobileSelect .content .panel .wheel {
  position: relative;
  z-index: 0;
  float: left;
  width: 50%;
  height: 200px;
  overflow: hidden;
  -webkit-transition: width 0.3s ease;
  transition: width 0.3s ease;
}
.mobileSelect .content .panel .wheel .selectContainer {
  display: block;
  text-align: center;
  -webkit-transition: -webkit-transform 0.18s ease-out;
  transition: -webkit-transform 0.18s ease-out;
  transition: transform 0.18s ease-out;
  transition: transform 0.18s ease-out, -webkit-transform 0.18s ease-out;
}
.mobileSelect .content .panel .wheel .selectContainer li {
  font-size: 20px;
  display: block;
  height: 40px;
  line-height: 40px;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.mobileSelect .content .panel .selectLine {
  height: 40px;
  width: 100%;
  position: absolute;
  top: 80px;
  pointer-events: none;
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
  border-top: 1px solid #DCDCDC;
  border-bottom: 1px solid #DCDCDC;
}
.mobileSelect .content .panel .shadowMask {
  position: absolute;
  top: 0;
  width: 100%;
  height: 200px;
  background: -webkit-gradient(linear, left top, left bottom, from(#ffffff), color-stop(rgba(255, 255, 255, 0)), to(#ffffff));
  background: -webkit-linear-gradient(top, #ffffff, rgba(255, 255, 255, 0), #ffffff);
  background: linear-gradient(to bottom, #ffffff, rgba(255, 255, 255, 0), #ffffff);
  opacity: 0.9;
  pointer-events: none;
}
.mobileSelect-show {
  opacity: 1;
  z-index: 10000;
  visibility: visible;
}
.mobileSelect-show .content {
  bottom: 0;
}

3、dateSelect.js

$.extend({
	//年月日
	selectYY_MM_DD: function(g, a, k) {
        var d, e, b  ;
        b = new Date;
        var starYear = b.getFullYear() - 55 ;//最小选项
        var maxYear = b.getFullYear()+5;//最大的选项 
        d = starYear; e = maxYear;
        b = [10,0,0];
        var dateVal = $(g).val(); //获取输入框的值 
        if( dateVal != undefined && dateVal != ""){ 
        		dateVal = dateVal.split("-");
            	//设置默认选择的项
            	dateVal && 3 == dateVal.length ? b = [dateVal[0] -  starYear , dateVal[1] -1 , dateVal[2] -1 ] : b = b; 
        } else{
            var nowDate = new Date;
            b=[nowDate.getFullYear()-starYear,nowDate.getMonth(),nowDate.getDate()-1]
        }
        new MobileSelect({
            trigger: g, 
            title: '选择时间',
            wheels: function(a, b) {
                for (var d = [{ data: []  }]; a <= b; a++) {
                    for (var e = { id: a, value: a , childs: [] }, c = 1; 12 >= c; c++) {
                        for (var h = [], g = (1 == c || 3 == c || 5 == c || 7 == c || 8 == c || 10 == c || 12 == c) ? 31 : 2 == c ? 0 == a % 4 && 0 != a % 100 ? 29 : 0 == a % 400 ? 29 : 28 : 30, f = 1; f <= g; f++) 
                        	h.push({ id: f < 10 ? '0' + f : f,  value: f < 10 ? '0' + f : f  });
                            e.childs.push({  id: c < 10 ? '0' + c : c,  value: c < 10 ? '0' + c : c , childs: h < 10 ? '0' + h :h })
                    }
                    d[0].data.push(e)
                }
                return d
            }(d, e),
            position: b,
            callback: function(a, b) {
            	if(k != undefined){
            		k({
                        year: b[0].id,
                        month: b[1].id,
                        day: b[2].id
                    })
            	} 
            }
        })
    }

	//年月
    ,selectDate_YM: function(el, cbFn) { 
        /*创建日期数据*/
        var createDateData = function(info) {
            var dateData = [{
                data: []
            }];
            var childData = [];

            for (var j = 1; j <= 12; j++) {
                if (j < 10) {
                    childData.push({
                        id: '0' + j,
                        value: '0' + j
                    });
                } else {
                    childData.push({
                        id: j,
                        value: j
                    });
                }
            }

            for (var i = info.startYear; i <= info.maxYear; i++) {
                dateData[0].data.push({
                    id: i,
                    value: i,
                    childs: childData
                });
            }
 

            return dateData;
        };

        var info = {},
        now = new Date();
        info.nowYear = now.getFullYear();
        info.nowMonth = (now.getMonth() + 1);
        info.startYear = info.nowYear - 60; //最小的选项 
        info.maxYear = info.nowYear + 3; //最大的选项
        var dateVal = $(el).val(); //获取输入框的值
        var tempos = [10, 0];
        if (dateVal != undefined && dateVal != "") { 
                dateVal = dateVal.split("-");
                //设置默认选择的项
                dateVal && 2 == dateVal.length ? tempos = [dateVal[0] - info.startYear, dateVal[1] - 1] : tempos = tempos; 
        }
        
      //年月 带有至今选项
        var selectDate_YM = new MobileSelect({
            trigger: el,
            title: '选择年月',
            wheels: createDateData(info),
            position: tempos,
            //设置默认选择的项
            callback: function(item, data) {
                if (data.length > 1) {
                    var dateInfo = {
                        year: data[0].id,
                        month: data[1].id,
                    };
                } else {
                    var dateInfo = {
                        year: data[0].id,
                    };
                }

                cbFn && cbFn(dateInfo);
            }
        });

    }
    //专门用于结束时间,有至今选项
    ,
    selectDate_YM_END: function(el, cbFn) {

        /*创建日期数据*/
        var createDateData = function(info) {
            var dateData = [{
                data: []
            }];
            var childData = [];

            for (var j = 1; j <= 12; j++) {
                if (j < 10) {
                    childData.push({
                        id: '0' + j,
                        value: '0' + j
                    });
                } else {
                    childData.push({
                        id: j,
                        value: j
                    });
                }
            }

            for (var i = info.startYear; i <= info.maxYear; i++) {
                dateData[0].data.push({
                    id: i,
                    value: i,
                    childs: childData
                });
            }

            //如果是结束日期的  加上至今选项
            if ($(el).data("type") == "end") dateData[0].data.push({
                id: info.maxYear + 1,
                value: "至今"
            });

            return dateData;
        };

        var info = {},
        now = new Date();
        info.nowYear = now.getFullYear();
        info.nowMonth = (now.getMonth() + 1);
        info.startYear = info.nowYear - 60; //最小的选项 
        info.maxYear = info.nowYear; //最大的选项
        var dateVal = $(el).val(); //获取输入框的值
        var tempos = [10, 0];
        if (dateVal != undefined && dateVal != "") {
            if (dateVal == "至今") {
                tempos = [info.maxYear - info.startYear + 1];
            } else {
                dateVal = dateVal.split("-");
                //设置默认选择的项
                dateVal && 2 == dateVal.length ? tempos = [dateVal[0] - info.startYear, dateVal[1] - 1] : tempos = tempos;
            }
        }

        var selectDate_YM_END = new MobileSelect({
            trigger: el,
            title: '选择年月',
            wheels: createDateData(info),
            position: tempos,
            //设置默认选择的项
            callback: function(item, data) {
                if (data.length > 1) {
                    var dateInfo = {
                        year: data[0].id,
                        month: data[1].id,
                    };
                } else {
                    var dateInfo = {
                        year: data[0].id,
                    };
                }

                cbFn && cbFn(dateInfo);
            }
        });

    }

    //年
   , selectDate_Y: function(el, cbFn) {

        /*创建日期数据*/
        var createDateData = function(info) {
            var dateData = [{
                data: []
            }];

            for (var i = info.startYear; i <= info.maxYear; i++) {
                dateData[0].data.push({
                    id: i,
                    value: i
                });
            } 

            return dateData;
        };

        var info = {},
        now = new Date();
        info.nowYear = now.getFullYear();
        info.nowMonth = (now.getMonth() + 1);
        info.startYear = info.nowYear - 60; //最小的选项 
        info.maxYear = info.nowYear ; //最大的选项
        var dateVal = $(el).val(); //获取输入框的值
        var tempos = [info.maxYear - info.startYear , 0];//设置初始值
        if (dateVal != undefined && dateVal != "") {
             
                dateVal = dateVal.split("-");
                //设置默认选择的项
                dateVal && 1 == dateVal.length ? tempos = [dateVal[0] - info.startYear] : tempos = tempos;
             
        }

        var selectDate_Y = new MobileSelect({
            trigger: el,
            title: '选择年份',
            wheels: createDateData(info),
            position: tempos,
            //设置默认选择的项
            callback: function(item, data) {
                if (data.length > 1) {
                    var dateInfo = {
                        year: data[0].id,

                    };
                } else {
                    var dateInfo = {
                        year: data[0].id,
                    };
                }

                cbFn && cbFn(dateInfo);
            }
        });

    }
   //时分
    ,select_HH_MM: function(el, cbFn) {

        /*创建日期数据*/
        var createDateData = function(info) {
            var dateData = [{
                data: []
            }];
            var childData = [];
            //分钟
            for (var j = 0; j <= 59; j++) {
                if (j < 10) {
                    childData.push({
                        id: '0' + j,
                        value: '0' + j
                    });
                } else {
                    childData.push({
                        id: j,
                        value: j
                    });
                }
            }
            //小时
            for (var i = info.startHour; i <= info.maxHour; i++) {
                var pra = i < 10 ? '0' + i: i 
                dateData[0].data.push({ id: pra,  value: pra, childs: childData  });
            }

            return dateData;
        };
        var info = {};
        info.startHour = 0;
        info.maxHour = 23;
        info.startMinute = 0; //最小的选项 
        info.maxMinute = 59; //最大的选项
        var designTimeVal = $(el).val(); //获取输入框的值
        var tempos = [0, 0];
        if (designTimeVal != undefined && designTimeVal != "") {
            designTimeVal = designTimeVal.split(":");
            //设置默认选择的项
            designTimeVal && 2 == designTimeVal.length ? tempos = [designTimeVal[0] - info.startHour, designTimeVal[1]] : tempos = tempos;
        }

        var select_HH_MM = new MobileSelect({
            trigger: el,
            title: '选择时分',
            connector: ':',
            wheels: createDateData(info),
            position: tempos,
            //设置默认选择的项
            callback: function(item, data) {
                if (data.length > 1) {
                    var dateInfo = {
                        year: data[0].id,
                        month: data[1].id,
                    };
                } else {
                    var dateInfo = {
                        year: data[0].id,
                    };
                }

                cbFn && cbFn(dateInfo);
            }
        });
    }
    //时分秒
    ,select_HH_MM_SS: function(el, cbFn) {

        /*创建日期数据*/
        var createDateData = function(info) {
            var dateData = [{
                data: []
            }];
            var childData = [] , childDatass = [];
            
            //秒钟
            for (var j = 0; j <= 59; j++) {
                if (j < 10) {
                	childDatass.push({
                        id: '0' + j,
                        value: '0' + j
                    });
                } else {
                	childDatass.push({
                        id: j,
                        value: j 
                    });
                }
            }
            //分钟
            for (var j = 0; j <= 59; j++) {
                if (j < 10) {
                    childData.push({
                        id: '0' + j,
                        value: '0' + j,
                        childs: childDatass
                    });
                } else {
                    childData.push({
                        id: j,
                        value: j,
                        childs: childDatass
                    });
                }
            }
            //小时
            for (var i = info.startHour; i <= info.maxHour; i++) {
                var pra = i < 10 ? '0' + i: i 
                dateData[0].data.push({ id: pra,  value: pra, childs: childData  });
            }

            return dateData;
        };
        var info = {};
        info.startHour = 0;
        info.maxHour = 23;
        info.startMinute = 0; //最小的选项 
        info.maxMinute = 59; //最大的选项
        var designTimeVal = $(el).val(); //获取输入框的值
        var tempos = [0, 0 , 0];
        if (designTimeVal != undefined && designTimeVal != "") {
            designTimeVal = designTimeVal.split(":");
            //设置默认选择的项
            designTimeVal && 3 == designTimeVal.length ? tempos = [designTimeVal[0] - info.startHour, designTimeVal[1] ,designTimeVal[2]] : tempos = tempos;
        }else{
            var nowDate = new Date;
            tempos=[nowDate.getFullYear(),nowDate.getMonth() + 1,nowDate.getDate()]
        }

        

        var select_HH_MM = new MobileSelect({
            trigger: el,
            title: '选择时分秒',
            connector: ':',
            wheels: createDateData(info),
            position: tempos,
            //设置默认选择的项
            callback: function(item, data) {
                if (data.length > 1) {
                    var dateInfo = {
                        year: data[0].id,
                        month: data[1].id,
                    };
                } else {
                    var dateInfo = {
                        year: data[0].id,
                    };
                }

                cbFn && cbFn(dateInfo);
            }
        });
    }
});

 mobileSelect.js

(function() {
	function getClass(dom,string) {
		return dom.getElementsByClassName(string);
	}
	//构造器
	function MobileSelect(config) {
		this.mobileSelect;
		this.wheelsData = config.wheels;
		this.jsonType =  false;
		this.cascadeJsonData = [];
		this.displayJson = []; 
		this.cascade = false;
		this.startY;
		this.moveEndY;
		this.moveY;
		this.oldMoveY;
		this.offset = 0;
		this.offsetSum = 0;
		this.oversizeBorder;
		this.curDistance = [];
		this.clickStatus = false;
		this.isPC = true;
		this.init(config);
	}
	MobileSelect.prototype = {
		constructor: MobileSelect,
		init: function(config){
			var _this = this; 
			_this.keyMap = config.keyMap ? config.keyMap : {id:'id', value:'value', childs:'childs'};
			_this.checkDataType();
			_this.renderWheels(_this.wheelsData, config.cancelBtnText, config.ensureBtnText);
			_this.trigger = document.querySelector(config.trigger);
			if(!_this.trigger){
				console.error('mobileSelect has been successfully installed, but no trigger found on your page.');
				return false;
			}
			_this.wheel = getClass(_this.mobileSelect,'wheel');
			_this.slider = getClass(_this.mobileSelect,'selectContainer'); 
			_this.wheels = _this.mobileSelect.querySelector('.wheels');
			_this.liHeight = _this.mobileSelect.querySelector('li').offsetHeight;
			_this.ensureBtn = _this.mobileSelect.querySelector('.ensure');
			_this.cancelBtn = _this.mobileSelect.querySelector('.cancel');
			_this.grayLayer = _this.mobileSelect.querySelector('.grayLayer');
			_this.popUp = _this.mobileSelect.querySelector('.content');
			_this.callback = config.callback ? config.callback : function(){};
			_this.transitionEnd = config.transitionEnd ? config.transitionEnd : function(){};
			_this.initPosition = config.position ? config.position : [];
			_this.titleText = config.title ? config.title : '';
			_this.connector = config.connector != undefined && config.connector != "" ? config.connector : '-';//拼接值的连接符
			_this.trigger.style.cursor='pointer';
			_this.setStyle(config);
			_this.setTitle(_this.titleText);
			_this.checkIsPC();
			_this.checkCascade();
			if (_this.cascade) {
				_this.initCascade();
			}
			//定位 初始位置
			if(_this.initPosition.length < _this.slider.length){
				var diff = _this.slider.length - _this.initPosition.length;
				for(var i=0; i<diff; i++){
					_this.initPosition.push(0);
				}
			}

			_this.setCurDistance(_this.initPosition);
			_this.addListenerAll();

			//按钮监听
			_this.cancelBtn.addEventListener('click',function(){
			_this.mobileSelect.classList.remove('mobileSelect-show');
		
			
		    });

			//点击确认选择
		    _this.ensureBtn.addEventListener('click',function(){
				_this.mobileSelect.classList.remove('mobileSelect-show');
				var tempValue ='',tempIdValue ='';
		    	for(var i=0; i<_this.wheel.length; i++){
		    		i==_this.wheel.length-1 ? tempValue += _this.getInnerHtml(i) : tempValue += _this.getInnerHtml(i) + _this.connector;
		    		i==_this.wheel.length-1 ? tempIdValue = _this.getDataId(i) : '';
				}
				
		    	_this.trigger.value = tempValue;
		    	$(_this.trigger).data("value",tempIdValue);//把编号赋值到输入框的data-value
		    	_this.callback(_this.getIndexArr(),_this.getValue());
		    });

		    _this.trigger.addEventListener('click',function(){
				_this.mobileSelect.classList.add('mobileSelect-show');
			
             
				// var date = new Date();
				// var year = date.getFullYear();
				// var month = date.getMonth() + 1;
				// var day = date.getDate();
				// if (month < 10) {
				// 	month = "0" + month;
				// }
				// if (day < 10) {
				// 	day = "0" + day;
				// }
				// console.log(year);
				// console.log(month);
				// console.log(day);



				$('.wheels').eq(0).find('li').attr("style","color:#000 !important")
				$('.wheels').eq(1).find('li').attr("style","color:#000 !important")
				var tempValue ='',tempIdValue ='';
				for(var i=0; i<_this.wheel.length; i++){
					i==_this.wheel.length-1 ? tempValue += _this.getInnerHtml(i) : tempValue += _this.getInnerHtml(i) + _this.connector;
					i==_this.wheel.length-1 ? tempIdValue = _this.getDataId(i) : '';
				}
				var ddd=tempValue.split("-")
				//console.log(ddd)
			
				var s1=$(".wheels").eq(0).find(".selectContainer")[0];
				var s2=$(".wheels").eq(0).find(".selectContainer")[1];
				var s3=$(".wheels").eq(0).find(".selectContainer")[2];


				$(s1).find("li").each(function(){
			
					var s=$(this)[0];
						if($(s).text()==ddd[0]){
							$(s).attr("style","color:red")
						}
					   //  alert($(resultNode).attr("id"))
					})
	
					$(s2).find("li").each(function(){
			
						var s=$(this)[0];
							if($(s).text()==ddd[1]){
								$(s).attr("style","color:red")
							}
						   //  alert($(resultNode).attr("id"))
						})
						
						$(s3).find("li").each(function(){
			
							var s=$(this)[0];
								if($(s).text()==ddd[2]){
									$(s).attr("style","color:red")
								}
							   //  alert($(resultNode).attr("id"))
							})



							var s4=$(".wheels").eq(1).find(".selectContainer")[0];
				var s5=$(".wheels").eq(1).find(".selectContainer")[1];
				var s6=$(".wheels").eq(1).find(".selectContainer")[2];
				$(s4).find("li").each(function(){
			
					var s=$(this)[0];
						if($(s).text()==ddd[0]){
							$(s).attr("style","color:red")
						}
					   //  alert($(resultNode).attr("id"))
					})
	
					$(s5).find("li").each(function(){
			
						var s=$(this)[0];
							if($(s).text()==ddd[1]){
								$(s).attr("style","color:red")
							}
						   //  alert($(resultNode).attr("id"))
						})
						
						$(s6).find("li").each(function(){
			
							var s=$(this)[0];
								if($(s).text()==ddd[2]){
									$(s).attr("style","color:red")
								}
							   //  alert($(resultNode).attr("id"))
							})


		    });
		    _this.grayLayer.addEventListener('click',function(){
		    	_this.mobileSelect.classList.remove('mobileSelect-show');
		    });
		    _this.popUp.addEventListener('click',function(){
		    	event.stopPropagation(); 
		    });

			_this.fixRowStyle(); //修正列数
		},

		setTitle: function(string){
			var _this = this;
			_this.titleText = string;
			_this.mobileSelect.querySelector('.title').innerHTML = _this.titleText;
		},

		setStyle: function(config){
			var _this = this;
			if(config.ensureBtnColor){
				_this.ensureBtn.style.color = config.ensureBtnColor;
			}
			if(config.cancelBtnColor){
				_this.cancelBtn.style.color = config.cancelBtnColor;
			}
			if(config.titleColor){
				_this.title = _this.mobileSelect.querySelector('.title');
				_this.title.style.color = config.titleColor;
			}
			if(config.textColor){
				_this.panel = _this.mobileSelect.querySelector('.panel');
				_this.panel.style.color = config.textColor;
			}
			if(config.titleBgColor){
				_this.btnBar = _this.mobileSelect.querySelector('.btnBar');
				_this.btnBar.style.backgroundColor = config.titleBgColor;
			}
			if(config.bgColor){
				_this.panel = _this.mobileSelect.querySelector('.panel');
				_this.shadowMask = _this.mobileSelect.querySelector('.shadowMask');
				_this.panel.style.backgroundColor = config.bgColor;
				_this.shadowMask.style.background = 'linear-gradient(to bottom, '+ config.bgColor + ', rgba(255, 255, 255, 0), '+ config.bgColor + ')';
			}
		},

		checkIsPC: function(){
			var _this = this;
		    var sUserAgent = navigator.userAgent.toLowerCase();
		    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
		    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
		    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
		    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
		    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
		    var bIsAndroid = sUserAgent.match(/android/i) == "android";
		    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
		    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
		    if ((bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM)) {
		        _this.isPC = false;
		    }
		},

		show: function(){
		    this.mobileSelect.classList.add('mobileSelect-show');	
		},

		renderWheels: function(wheelsData, cancelBtnText, ensureBtnText){
			var _this = this;
			var cancelText = cancelBtnText ? cancelBtnText : '取消';
			var ensureText = ensureBtnText ? ensureBtnText : '确认';
			_this.mobileSelect = document.createElement("div");
			_this.mobileSelect.className = "mobileSelect";
			_this.mobileSelect.innerHTML = 
		    	'<div class="grayLayer"></div>'+
		        '<div class="content">'+
		            '<div class="btnBar">'+
		                '<div class="fixWidth">'+
		                    '<div class="cancel">'+ cancelText +'</div>'+
		                    '<div class="title"></div>'+
		                    '<div class="ensure">'+ ensureText +'</div>'+
		                '</div>'+
		            '</div>'+
		            '<div class="panel">'+
		                '<div class="fixWidth">'+
		                	'<div class="wheels">'+
			                '</div>'+
		                    '<div class="selectLine"><span>年</span><span>月</span><span>日</span></div>'+
		                    '<div class="shadowMask"></div>'+
		                '</div>'+
		            '</div>'+
		        '</div>';
		    document.body.appendChild(_this.mobileSelect);

			//根据数据长度来渲染

			var tempHTML='';
			for(var i=0; i<wheelsData.length; i++){ 
			//列
				tempHTML += '<div class="wheel"><ul class="selectContainer">';
				if(_this.jsonType){
					for(var j=0; j<wheelsData[i].data.length; j++){ 
					//行
						tempHTML += '<li data-id="'+wheelsData[i].data[j][_this.keyMap.id]+'">'+wheelsData[i].data[j][_this.keyMap.value]+'</li>';
					}
				}else{
					for(var j=0; j<wheelsData[i].data.length; j++){ 
					//行
						tempHTML += '<li>'+wheelsData[i].data[j]+'</li>';
					}
				}
				tempHTML += '</ul></div>';
			}
			_this.mobileSelect.querySelector('.wheels').innerHTML = tempHTML;
		},

		addListenerAll: function(){
			var _this = this;
			for(var i=0; i<_this.slider.length; i++){
				//手势监听
				(function (i) {
					_this.addListenerWheel(_this.wheel[i], i);
					_this.addListenerLi(i);
				})(i);
			}
		},

		addListenerWheel: function(theWheel, index){
			var _this = this;
			theWheel.addEventListener('touchstart', function () {
				_this.touch(event, this.firstChild, index);
			},false);
			theWheel.addEventListener('touchend', function () {
				_this.touch(event, this.firstChild, index);
			},false);
			theWheel.addEventListener('touchmove', function () {
				_this.touch(event, this.firstChild, index);
			},false);

			if(_this.isPC){
				//如果是PC端则再增加拖拽监听 方便调试
				theWheel.addEventListener('mousedown', function () {
					_this.dragClick(event, this.firstChild, index);
				},false);
				theWheel.addEventListener('mousemove', function () {
					_this.dragClick(event, this.firstChild, index);
				},false);
				theWheel.addEventListener('mouseup', function () {
					_this.dragClick(event, this.firstChild, index);
				},true); 
			}
		},

		addListenerLi:function(sliderIndex){
			var _this = this;
			var curWheelLi = _this.slider[sliderIndex].getElementsByTagName('li');
			for(var j=0; j<curWheelLi.length;j++){
				(function (j) {
					curWheelLi[j].addEventListener('click',function(){
						_this.singleClick(this, j, sliderIndex);
					},false);
				})(j);
			}
		},

		checkDataType: function(){ 
			var _this = this;
			if(typeof(_this.wheelsData[0].data[0])=='object'){
				_this.jsonType = true;
			}
		},

		checkCascade: function(){
			var _this = this;
			if(_this.jsonType){ 
				var node = _this.wheelsData[0].data;
				for(var i=0; i<node.length; i++){
					if(_this.keyMap.childs in node[i] && node[i][_this.keyMap.childs].length > 0){
						_this.cascade = true;
						_this.cascadeJsonData = _this.wheelsData[0].data;
						break;
					}
				}
			}else{
				_this.cascade = false;
			}
		},

		generateArrData: function (targetArr) {
			var tempArr = [];
			var keyMap_id = this.keyMap.id;
			var keyMap_value = this.keyMap.value;
			for(var i=0; i<targetArr.length; i++){
				var tempObj = {}; 
				tempObj[keyMap_id] = targetArr[i][this.keyMap.id];
				tempObj[keyMap_value] = targetArr[i][this.keyMap.value];
				tempArr.push(tempObj);	
			}
			return tempArr;
		},

		initCascade: function(){
			var _this = this;
			_this.displayJson.push(_this.generateArrData(_this.cascadeJsonData));
			if(_this.initPosition.length>0){
				_this.initDeepCount = 0;
				_this.initCheckArrDeep(_this.cascadeJsonData[_this.initPosition[0]]);
			}else{
				_this.checkArrDeep(_this.cascadeJsonData[0]);
			}
			_this.reRenderWheels();
		},

		initCheckArrDeep: function (parent) {
			var _this = this;
			if(parent){
				if (_this.keyMap.childs in parent && parent[_this.keyMap.childs].length > 0) {
					_this.displayJson.push(_this.generateArrData(parent[_this.keyMap.childs])); 
					_this.initDeepCount++;
					var nextNode = parent[_this.keyMap.childs][_this.initPosition[_this.initDeepCount]];
					if(nextNode){
						_this.initCheckArrDeep(nextNode);
					}else{
						_this.checkArrDeep(parent[_this.keyMap.childs][0]);
					}
				}
			}
		},

		checkArrDeep: function (parent) { 
			//检测子节点深度  修改 displayJson
			var _this = this;
			if(parent){
				if (_this.keyMap.childs in parent && parent[_this.keyMap.childs].length > 0) {
					_this.displayJson.push(_this.generateArrData(parent[_this.keyMap.childs])); //生成子节点数组
					_this.checkArrDeep(parent[_this.keyMap.childs][0]);//检测下一个子节点
				}
			}
		},

		checkRange: function(index, posIndexArr){
			var _this = this;
			var deleteNum = _this.displayJson.length-1-index;
			for(var i=0; i<deleteNum; i++){
				_this.displayJson.pop(); //修改 displayJson
			}
			var resultNode;
			for (var i = 0; i <= index; i++){
				if (i == 0)
					resultNode = _this.cascadeJsonData[posIndexArr[0]];
				else {
					resultNode = resultNode[_this.keyMap.childs][posIndexArr[i]];
				}
			}
			_this.checkArrDeep(resultNode);
			//console.log(_this.displayJson);
			_this.reRenderWheels();
			_this.fixRowStyle();
			_this.setCurDistance(_this.resetPostion(index, posIndexArr));



			// $('.wheels').eq(0).attr("style","color:yellow !important")
			// $('.wheels').eq(1).attr("style","color:yellow !important")
			var tempValue ='',tempIdValue ='';
			for(var i=0; i<_this.wheel.length; i++){
				i==_this.wheel.length-1 ? tempValue += _this.getInnerHtml(i) : tempValue += _this.getInnerHtml(i) + _this.connector;
				i==_this.wheel.length-1 ? tempIdValue = _this.getDataId(i) : '';
			}
			var ddd=tempValue.split("-")
			//console.log(ddd)
		

			$('.wheels').eq(0).find('li').attr("style","color:#000 !important")
			$('.wheels').eq(1).find('li').attr("style","color:#000 !important")

			var s1=$(".wheels").find(".selectContainer")[0];
			var s2=$(".wheels").find(".selectContainer")[1];
			var s3=$(".wheels").find(".selectContainer")[2];
		

			$(s1).find("li").each(function(){
		
				var s=$(this)[0];
					if($(s).text()==ddd[0]){
						$(s).attr("style","color:red")
					}
				   //  alert($(resultNode).attr("id"))
				})

				$(s2).find("li").each(function(){
		
					var s=$(this)[0];
						if($(s).text()==ddd[1]){
							$(s).attr("style","color:red")
						}
					   //  alert($(resultNode).attr("id"))
					})
					
					$(s3).find("li").each(function(){
		
						var s=$(this)[0];
							if($(s).text()==ddd[2]){
								$(s).attr("style","color:red")
							}
						   //  alert($(resultNode).attr("id"))
						})

						var s4=$(".wheels").eq(1).find(".selectContainer")[0];
				var s5=$(".wheels").eq(1).find(".selectContainer")[1];
				var s6=$(".wheels").eq(1).find(".selectContainer")[2];
				$(s4).find("li").each(function(){
			
					var s=$(this)[0];
						if($(s).text()==ddd[0]){
							$(s).attr("style","color:red")
						}
					   //  alert($(resultNode).attr("id"))
					})
	
					$(s5).find("li").each(function(){
			
						var s=$(this)[0];
							if($(s).text()==ddd[1]){
								$(s).attr("style","color:red")
							}
						   //  alert($(resultNode).attr("id"))
						})
						
						$(s6).find("li").each(function(){
			
							var s=$(this)[0];
								if($(s).text()==ddd[2]){
									$(s).attr("style","color:red")
								}
							   //  alert($(resultNode).attr("id"))
							})



		},

		resetPostion: function(index, posIndexArr){
			var _this = this;
			var tempPosArr = posIndexArr;
			var tempCount;
			if(_this.slider.length > posIndexArr.length){ 
				tempCount = _this.slider.length - posIndexArr.length;
				for(var i=0; i<tempCount; i++){  
					tempPosArr.push(0);
				}
			}else if(_this.slider.length < posIndexArr.length){
				tempCount = posIndexArr.length - _this.slider.length;
				for(var i=0; i<tempCount; i++){
					tempPosArr.pop();
				}	
			}
			for(var i=index+1; i< tempPosArr.length; i++){
				tempPosArr[i] = 0;
			} 
			return tempPosArr;
		},

		reRenderWheels: function(){
			var _this = this;
			//删除多余的wheel
			if(_this.wheel.length > _this.displayJson.length){
				var count = _this.wheel.length - _this.displayJson.length;
				for(var i=0; i<count; i++){
					_this.wheels.removeChild(_this.wheel[_this.wheel.length-1]);
				}
			}
			for(var i=0; i<_this.displayJson.length; i++){ 
			//列
				(function (i) {
					var tempHTML='';
					if(_this.wheel[i]){
						//console.log('插入Li');
						for(var j=0; j<_this.displayJson[i].length; j++){ 
						//行
							tempHTML += '<li data-id="'+_this.displayJson[i][j][_this.keyMap.id]+'">'+_this.displayJson[i][j][_this.keyMap.value]+'</li>';
						}
						_this.slider[i].innerHTML = tempHTML;

					}else{
						var tempWheel = document.createElement("div");
						tempWheel.className = "wheel";
						tempHTML = '<ul class="selectContainer">';
						for(var j=0; j<_this.displayJson[i].length; j++){ 
						//行
							tempHTML += '<li data-id="'+_this.displayJson[i][j][_this.keyMap.id]+'">'+_this.displayJson[i][j][_this.keyMap.value]+'</li>';
						}
						tempHTML += '</ul>';
						tempWheel.innerHTML = tempHTML;

						_this.addListenerWheel(tempWheel, i);
				    	_this.wheels.appendChild(tempWheel); 
					}
					_this.addListenerLi(i);
				})(i);
			}
		},

		updateWheels:function(data){
			var _this = this;
			if(_this.cascade){
				_this.cascadeJsonData = data;
				_this.displayJson = [];
				_this.initCascade();
				if(_this.initPosition.length < _this.slider.length){
					var diff = _this.slider.length - _this.initPosition.length;
					for(var i=0; i<diff; i++){
						_this.initPosition.push(0);
					}
				}
				_this.setCurDistance(_this.initPosition);
				_this.fixRowStyle();
			}
		},

		updateWheel: function(sliderIndex, data){
			var _this = this;
			var tempHTML='';
	    	if(_this.cascade){
	    		console.error('级联格式不支持updateWheel(),请使用updateWheels()更新整个数据源');
				return false;
	    	}
	    	else if(_this.jsonType){
				for(var j=0; j<data.length; j++){
					tempHTML += '<li data-id="'+data[j][_this.keyMap.id]+'">'+data[j][_this.keyMap.value]+'</li>';
				}
				_this.wheelsData[sliderIndex] = {data: data};
	    	}else{
				for(var j=0; j<data.length; j++){
					tempHTML += '<li>'+data[j]+'</li>';
				}
				_this.wheelsData[sliderIndex] = data;
	    	}
			_this.slider[sliderIndex].innerHTML = tempHTML;
			_this.addListenerLi(sliderIndex);
		},

		fixRowStyle: function(){
			var _this = this;
			var width = (100/_this.wheel.length).toFixed(2);
			for(var i=0; i<_this.wheel.length; i++){
				_this.wheel[i].style.width = width+'%';
			}
		},

	    getIndex: function(distance){
	        return Math.round((2*this.liHeight-distance)/this.liHeight);
	    },

	    getIndexArr: function(){
	    	var _this = this;
	    	var temp = [];
	    	for(var i=0; i<_this.curDistance.length; i++){
	    		temp.push(_this.getIndex(_this.curDistance[i]));
	    	}
	    	return temp;
	    },

	    getValue: function(){
	    	var _this = this;
	    	var temp = [];
	    	var positionArr = _this.getIndexArr();
	    	if(_this.cascade){
		    	for(var i=0; i<_this.wheel.length; i++){
		    		temp.push(_this.displayJson[i][positionArr[i]]);
		    	}
	    	}
	    	else if(_this.jsonType){
		    	for(var i=0; i<_this.curDistance.length; i++){
		    		temp.push(_this.wheelsData[i].data[_this.getIndex(_this.curDistance[i])]);
		    	}
	    	}else{
		    	for(var i=0; i<_this.curDistance.length; i++){
		    		temp.push(_this.getInnerHtml(i));
		    	}
	    	}
	    	return temp;
	    },

	    calcDistance: function(index){
			return 2*this.liHeight-index*this.liHeight;
	    },

	    setCurDistance: function(indexArr){
	    	var _this = this;
	    	var temp = [];
	    	for(var i=0; i<_this.slider.length; i++){
	    		temp.push(_this.calcDistance(indexArr[i]));
	    		_this.movePosition(_this.slider[i],temp[i]);
	    	}
	    	_this.curDistance = temp;
	    },

	    fixPosition: function(distance){
	        return -(this.getIndex(distance)-2)*this.liHeight;
	    },

	    movePosition: function(theSlider, distance){

	        theSlider.style.webkitTransform = 'translate3d(0,' + distance + 'px, 0)';
			theSlider.style.transform = 'translate3d(0,' + distance + 'px, 0)';
		
	    },

	    locatePostion: function(index, posIndex){
	    	this.curDistance[index] = this.calcDistance(posIndex);
	    	this.movePosition(this.slider[index],this.curDistance[index]);
	    },

	    updateCurDistance: function(theSlider, index){
			this.curDistance[index] = parseInt(theSlider.style.transform.split(',')[1]);

	    },

	    getDistance:function(theSlider){
	    	return parseInt(theSlider.style.transform.split(',')[1]);
	    },

	    getInnerHtml: function(sliderIndex){
	    	var _this = this;
	    	var index = _this.getIndex(_this.curDistance[sliderIndex]);
	    	return _this.slider[sliderIndex].getElementsByTagName('li')[index].innerHTML;
	    },
	    getDataId: function(sliderIndex){
	    	var _this = this;
			var index = _this.getIndex(_this.curDistance[sliderIndex]);
			// console.log(index)
	    	return _this.slider[sliderIndex].getElementsByTagName('li')[index].dataset.id;
	    },

	    touch: function(event, theSlider, index){
	    	var _this = this;
	    	event = event || window.event;
	    	switch(event.type){
	    		case "touchstart":
			        _this.startY = event.touches[0].clientY;
			        _this.oldMoveY = _this.startY;
	    			break;

	    		case "touchend":

			        _this.moveEndY = event.changedTouches[0].clientY;
			        _this.offsetSum = _this.moveEndY - _this.startY;

					//修正位置
			        _this.updateCurDistance(theSlider, index);
					_this.curDistance[index] = _this.fixPosition(_this.curDistance[index]);
					
					_this.movePosition(theSlider, _this.curDistance[index]);
					
			        _this.oversizeBorder = -(theSlider.getElementsByTagName('li').length-3)*_this.liHeight; 


			        //反弹
			        if(_this.curDistance[index] + _this.offsetSum > 2*_this.liHeight){
			            _this.curDistance[index] = 2*_this.liHeight;
			            setTimeout(function(){
			                _this.movePosition(theSlider, _this.curDistance[index]);
			            }, 100);

			        }else if(_this.curDistance[index] + _this.offsetSum < _this.oversizeBorder){
			            _this.curDistance[index] = _this.oversizeBorder;
			            setTimeout(function(){
			                _this.movePosition(theSlider, _this.curDistance[index]);
			            }, 100);
			        }


			        _this.transitionEnd(_this.getIndexArr(),_this.getValue());

			        if(_this.cascade){
				        var tempPosArr = _this.getIndexArr();
				        tempPosArr[index] = _this.getIndex(_this.curDistance[index]);
			        	_this.checkRange(index, tempPosArr);
			        }

	    			break;

	    		case "touchmove":
			        event.preventDefault();
			        _this.moveY = event.touches[0].clientY;
			        _this.offset = _this.moveY - _this.oldMoveY;

			        _this.updateCurDistance(theSlider, index);
			        _this.curDistance[index] = _this.curDistance[index] + _this.offset;
			        _this.movePosition(theSlider, _this.curDistance[index]);
			        _this.oldMoveY = _this.moveY;
	    			break;
	    	}
	    },

	    dragClick: function(event, theSlider, index){
	    	var _this = this;
	    	event = event || window.event;
	    	switch(event.type){
	    		case "mousedown":
			        _this.startY = event.clientY;
			        _this.oldMoveY = _this.startY;
			        _this.clickStatus = true;
	    			break;

	    		case "mouseup":

			        _this.moveEndY = event.clientY;
			        _this.offsetSum = _this.moveEndY - _this.startY;

					//修正位置
			        _this.updateCurDistance(theSlider, index);
			        _this.curDistance[index] = _this.fixPosition(_this.curDistance[index]);
			        _this.movePosition(theSlider, _this.curDistance[index]);
			        _this.oversizeBorder = -(theSlider.getElementsByTagName('li').length-3)*_this.liHeight; 


			        //反弹
			        if(_this.curDistance[index] + _this.offsetSum > 2*_this.liHeight){
			            _this.curDistance[index] = 2*_this.liHeight;
			            setTimeout(function(){
			                _this.movePosition(theSlider, _this.curDistance[index]);
			            }, 100);

			        }else if(_this.curDistance[index] + _this.offsetSum < _this.oversizeBorder){
			            _this.curDistance[index] = _this.oversizeBorder;
			            setTimeout(function(){
			                _this.movePosition(theSlider, _this.curDistance[index]);
			            }, 100);
			        }

			        _this.clickStatus = false;
			        _this.transitionEnd(_this.getIndexArr(),_this.getValue());
			        if(_this.cascade){
				        var tempPosArr = _this.getIndexArr();
				        tempPosArr[index] = _this.getIndex(_this.curDistance[index]);
			        	_this.checkRange(index, tempPosArr);
			        }
	    			break;

	    		case "mousemove":
			        event.preventDefault();
			        if(_this.clickStatus){
				        _this.moveY = event.clientY;
				        _this.offset = _this.moveY - _this.oldMoveY;
				        _this.updateCurDistance(theSlider, index);
				        _this.curDistance[index] = _this.curDistance[index] + _this.offset;
				        _this.movePosition(theSlider, _this.curDistance[index]);
				        _this.oldMoveY = _this.moveY;
			        }
	    			break;
	    	}
	    },

	    singleClick: function(theLi, index, sliderIndex){
	    	var _this = this;
	        if(_this.cascade){
		        var tempPosArr = _this.getIndexArr();
		        tempPosArr[sliderIndex] = index;
	        	_this.checkRange(sliderIndex, tempPosArr);

	        }else{
		        _this.curDistance[sliderIndex] = (2-index)*_this.liHeight;
		        _this.movePosition(theLi.parentNode, _this.curDistance[sliderIndex]);
	        }
	    }

	};

	if (typeof exports == "object") {
		module.exports = MobileSelect;
	} else if (typeof define == "function" && define.amd) {
		define([], function () {
			return MobileSelect;
		})
	} else {
		window.MobileSelect = MobileSelect;
	}
})();

 

原创文章 79 获赞 56 访问量 17万+

猜你喜欢

转载自blog.csdn.net/qq_23009105/article/details/105827083