iosselect.js 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706
  1. /**
  2. * IosSelect
  3. * @param {number} level 选择的层级 1 2 3 4 5 6 最多支持6层
  4. * @param {...Array} data [oneLevelData[, twoLevelData[, threeLevelData[, fourLevelData[, fiveLevelData[, sixLevelData]]]]]] 可以用数组,也可以用方法
  5. * @param {Object} options
  6. * @param {string=} options.container 组件插入到该元素下 可选
  7. * @param {Function} options.callback 选择完毕后的回调函数
  8. * @param {Function} options.fallback 选择取消后的回调函数
  9. * @param {Function} options.maskCallback 点击背景层关闭组件时触发的方法
  10. * @param {string=} options.title 选择框title
  11. * @param {number=} options.itemHeight 每一项的高度,默认 35
  12. * @param {number=} options.itemShowCount 组件展示的项数,默认 7,可选3,5,7,9,不过不是3,5,7,9则展示7项
  13. * @param {number=} options.headerHeight 组件标题栏高度 默认 44
  14. * @param {css=} options.cssUnit px或者rem 默认是px
  15. * @param {string=} options.addClassName 组件额外类名 用于自定义样式
  16. * @param {...Array=} options.relation 数组 [oneTwoRelation, twoThreeRelation, threeFourRelation, fourFiveRelation] 默认值:[0, 0, 0, 0, 0, 0]
  17. * @param {number=} options.relation.oneTwoRelation 第一列和第二列是否通过parentId关联
  18. * @param {number=} options.relation.twoThreeRelation 第二列和第三列是否通过parentId关联
  19. * @param {number=} options.relation.threeFourRelation 第三列和第四列是否通过parentId关联
  20. * @param {number=} options.relation.fourFiveRelation 第四列和第五列是否通过parentId关联
  21. * @param {number=} options.relation.fiveSixRelation 第五列和第六列是否通过parentId关联
  22. * @param {string=} options.oneLevelId 第一级选中id
  23. * @param {string=} options.twoLevelId 第二级选中id
  24. * @param {string=} options.threeLevelId 第三级选中id
  25. * @param {string=} options.fourLevelId 第四级选中id
  26. * @param {string=} options.fiveLevelId 第五级选中id
  27. * @param {string=} options.sixLevelId 第六级选中id
  28. * @param {boolean=} options.showLoading 如果你的数据是异步加载的,可以使用该参数设置为true,下拉菜单会有加载中的效果
  29. * @param {boolean=} options.showAnimate 是否需要入场动画和退场动画,如需自定义动画效果,请修改css
  30. */
  31. (function() {
  32. /* modify by zhoushengmufc,based on iScroll v5.2.0 */
  33. var rAF = window.requestAnimationFrame ||
  34. window.webkitRequestAnimationFrame ||
  35. window.mozRequestAnimationFrame ||
  36. window.oRequestAnimationFrame ||
  37. window.msRequestAnimationFrame ||
  38. function (callback) { window.setTimeout(callback, 1000 / 60); };
  39. var aF = (function () {
  40. var eleStyle = document.createElement('div').style;
  41. var verdors = ['a', 'webkitA', 'MozA', 'OA', 'msA'];
  42. var endEvents = ['animationend', 'webkitAnimationEnd', 'animationend', 'oAnimationEnd', 'MSAnimationEnd'];
  43. var animation;
  44. for (var i = 0, len = verdors.length; i < len; i++) {
  45. animation = verdors[i] + 'nimation';
  46. if (animation in eleStyle) {
  47. return endEvents[i];
  48. }
  49. }
  50. return 'animationend';
  51. }());
  52. var utils = (function () {
  53. var me = {};
  54. var _elementStyle = document.createElement('div').style;
  55. var _vendor = (function () {
  56. var vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'],
  57. transform,
  58. i = 0,
  59. l = vendors.length;
  60. for ( ; i < l; i++ ) {
  61. transform = vendors[i] + 'ransform';
  62. if ( transform in _elementStyle ) return vendors[i].substr(0, vendors[i].length-1);
  63. }
  64. return false;
  65. })();
  66. function _prefixStyle (style) {
  67. if ( _vendor === false ) return false;
  68. if ( _vendor === '' ) return style;
  69. return _vendor + style.charAt(0).toUpperCase() + style.substr(1);
  70. }
  71. me.getTime = Date.now || function getTime () { return new Date().getTime(); };
  72. me.extend = function (target, obj) {
  73. for ( var i in obj ) {
  74. target[i] = obj[i];
  75. }
  76. };
  77. me.addEvent = function (el, type, fn, capture) {
  78. el.addEventListener(type, fn, !!capture);
  79. };
  80. me.removeEvent = function (el, type, fn, capture) {
  81. el.removeEventListener(type, fn, !!capture);
  82. };
  83. me.prefixPointerEvent = function (pointerEvent) {
  84. return window.MSPointerEvent ?
  85. 'MSPointer' + pointerEvent.charAt(7).toUpperCase() + pointerEvent.substr(8):
  86. pointerEvent;
  87. };
  88. me.momentum = function (current, start, time, lowerMargin, wrapperSize, deceleration) {
  89. var distance = current - start,
  90. speed = Math.abs(distance) / time,
  91. destination,
  92. duration;
  93. deceleration = deceleration === undefined ? 0.0006 : deceleration;
  94. destination = current + ( speed * speed ) / ( 2 * deceleration ) * ( distance < 0 ? -1 : 1 );
  95. duration = speed / deceleration;
  96. if ( destination < lowerMargin ) {
  97. destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin;
  98. distance = Math.abs(destination - current);
  99. duration = distance / speed;
  100. } else if ( destination > 0 ) {
  101. destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0;
  102. distance = Math.abs(current) + destination;
  103. duration = distance / speed;
  104. }
  105. return {
  106. destination: Math.round(destination),
  107. duration: duration
  108. };
  109. };
  110. var _transform = _prefixStyle('transform');
  111. me.extend(me, {
  112. hasTransform: _transform !== false,
  113. hasPerspective: _prefixStyle('perspective') in _elementStyle,
  114. hasTouch: 'ontouchstart' in window,
  115. hasPointer: !!(window.PointerEvent || window.MSPointerEvent), // IE10 is prefixed
  116. hasTransition: _prefixStyle('transition') in _elementStyle
  117. });
  118. /*
  119. This should find all Android browsers lower than build 535.19 (both stock browser and webview)
  120. - galaxy S2 is ok
  121. - 2.3.6 : `AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1`
  122. - 4.0.4 : `AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30`
  123. - galaxy S3 is badAndroid (stock brower, webview)
  124. `AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30`
  125. - galaxy S4 is badAndroid (stock brower, webview)
  126. `AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30`
  127. - galaxy S5 is OK
  128. `AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Mobile Safari/537.36 (Chrome/)`
  129. - galaxy S6 is OK
  130. `AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Mobile Safari/537.36 (Chrome/)`
  131. */
  132. me.isBadAndroid = (function() {
  133. var appVersion = window.navigator.appVersion;
  134. // Android browser is not a chrome browser.
  135. if (/Android/.test(appVersion) && !(/Chrome\/\d/.test(appVersion))) {
  136. var safariVersion = appVersion.match(/Safari\/(\d+.\d)/);
  137. if(safariVersion && typeof safariVersion === "object" && safariVersion.length >= 2) {
  138. return parseFloat(safariVersion[1]) < 535.19;
  139. } else {
  140. return true;
  141. }
  142. } else {
  143. return false;
  144. }
  145. })();
  146. me.extend(me.style = {}, {
  147. transform: _transform,
  148. transitionTimingFunction: _prefixStyle('transitionTimingFunction'),
  149. transitionDuration: _prefixStyle('transitionDuration'),
  150. transitionDelay: _prefixStyle('transitionDelay'),
  151. transformOrigin: _prefixStyle('transformOrigin')
  152. });
  153. me.hasClass = function (e, c) {
  154. var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
  155. return re.test(e.className);
  156. };
  157. me.addClass = function (e, c) {
  158. if ( me.hasClass(e, c) ) {
  159. return;
  160. }
  161. var newclass = e.className.split(' ');
  162. newclass.push(c);
  163. e.className = newclass.join(' ');
  164. };
  165. me.removeClass = function (e, c) {
  166. if ( !me.hasClass(e, c) ) {
  167. return;
  168. }
  169. var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
  170. e.className = e.className.replace(re, ' ');
  171. };
  172. me.offset = function (el) {
  173. var left = -el.offsetLeft,
  174. top = -el.offsetTop;
  175. // jshint -W084
  176. while (el = el.offsetParent) {
  177. left -= el.offsetLeft;
  178. top -= el.offsetTop;
  179. }
  180. // jshint +W084
  181. return {
  182. left: left,
  183. top: top
  184. };
  185. };
  186. me.preventDefaultException = function (el, exceptions) {
  187. for ( var i in exceptions ) {
  188. if ( exceptions[i].test(el[i]) ) {
  189. return true;
  190. }
  191. }
  192. return false;
  193. };
  194. me.extend(me.eventType = {}, {
  195. touchstart: 1,
  196. touchmove: 1,
  197. touchend: 1,
  198. mousedown: 2,
  199. mousemove: 2,
  200. mouseup: 2,
  201. pointerdown: 3,
  202. pointermove: 3,
  203. pointerup: 3,
  204. MSPointerDown: 3,
  205. MSPointerMove: 3,
  206. MSPointerUp: 3
  207. });
  208. me.extend(me.ease = {}, {
  209. quadratic: {
  210. style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
  211. fn: function (k) {
  212. return k * ( 2 - k );
  213. }
  214. },
  215. circular: {
  216. style: 'cubic-bezier(0.1, 0.57, 0.1, 1)', // Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1)
  217. fn: function (k) {
  218. return Math.sqrt( 1 - ( --k * k ) );
  219. }
  220. },
  221. back: {
  222. style: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)',
  223. fn: function (k) {
  224. var b = 4;
  225. return ( k = k - 1 ) * k * ( ( b + 1 ) * k + b ) + 1;
  226. }
  227. },
  228. bounce: {
  229. style: '',
  230. fn: function (k) {
  231. if ( ( k /= 1 ) < ( 1 / 2.75 ) ) {
  232. return 7.5625 * k * k;
  233. } else if ( k < ( 2 / 2.75 ) ) {
  234. return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
  235. } else if ( k < ( 2.5 / 2.75 ) ) {
  236. return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
  237. } else {
  238. return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
  239. }
  240. }
  241. },
  242. elastic: {
  243. style: '',
  244. fn: function (k) {
  245. var f = 0.22,
  246. e = 0.4;
  247. if ( k === 0 ) { return 0; }
  248. if ( k == 1 ) { return 1; }
  249. return ( e * Math.pow( 2, - 10 * k ) * Math.sin( ( k - f / 4 ) * ( 2 * Math.PI ) / f ) + 1 );
  250. }
  251. }
  252. });
  253. me.tap = function (e, eventName) {
  254. var ev = document.createEvent('Event');
  255. ev.initEvent(eventName, true, true);
  256. ev.pageX = e.pageX;
  257. ev.pageY = e.pageY;
  258. e.target.dispatchEvent(ev);
  259. };
  260. me.click = function (e) {
  261. var target = e.target,
  262. ev;
  263. if ( !(/(SELECT|INPUT|TEXTAREA)/i).test(target.tagName) ) {
  264. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent
  265. // initMouseEvent is deprecated.
  266. ev = document.createEvent(window.MouseEvent ? 'MouseEvents' : 'Event');
  267. ev.initEvent('click', true, true);
  268. ev.view = e.view || window;
  269. ev.detail = 1;
  270. ev.screenX = target.screenX || 0;
  271. ev.screenY = target.screenY || 0;
  272. ev.clientX = target.clientX || 0;
  273. ev.clientY = target.clientY || 0;
  274. ev.ctrlKey = !!e.ctrlKey;
  275. ev.altKey = !!e.altKey;
  276. ev.shiftKey = !!e.shiftKey;
  277. ev.metaKey = !!e.metaKey;
  278. ev.button = 0;
  279. ev.relatedTarget = null;
  280. ev._constructed = true;
  281. target.dispatchEvent(ev);
  282. }
  283. };
  284. return me;
  285. })();
  286. function IScrollForIosSelect (el, options) {
  287. this.wrapper = typeof el == 'string' ? document.querySelector(el) : el;
  288. this.scroller = this.wrapper.children[0];
  289. this.scrollerStyle = this.scroller.style; // cache style for better performance
  290. this.options = {
  291. disablePointer: true,
  292. disableTouch: !utils.hasTouch,
  293. disableMouse: utils.hasTouch,
  294. startX: 0,
  295. startY: 0,
  296. scrollY: true,
  297. directionLockThreshold: 5,
  298. momentum: true,
  299. bounce: true,
  300. bounceTime: 600,
  301. bounceEasing: '',
  302. preventDefault: true,
  303. preventDefaultException: { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ },
  304. HWCompositing: true,
  305. useTransition: true,
  306. useTransform: true,
  307. bindToWrapper: typeof window.onmousedown === "undefined"
  308. };
  309. for ( var i in options ) {
  310. this.options[i] = options[i];
  311. }
  312. // Normalize options
  313. this.translateZ = this.options.HWCompositing && utils.hasPerspective ? ' translateZ(0)' : '';
  314. this.options.useTransition = utils.hasTransition && this.options.useTransition;
  315. this.options.useTransform = utils.hasTransform && this.options.useTransform;
  316. this.options.eventPassthrough = this.options.eventPassthrough === true ? 'vertical' : this.options.eventPassthrough;
  317. this.options.preventDefault = !this.options.eventPassthrough && this.options.preventDefault;
  318. // If you want eventPassthrough I have to lock one of the axes
  319. this.options.scrollY = this.options.eventPassthrough == 'vertical' ? false : this.options.scrollY;
  320. this.options.scrollX = this.options.eventPassthrough == 'horizontal' ? false : this.options.scrollX;
  321. // With eventPassthrough we also need lockDirection mechanism
  322. this.options.freeScroll = this.options.freeScroll && !this.options.eventPassthrough;
  323. this.options.directionLockThreshold = this.options.eventPassthrough ? 0 : this.options.directionLockThreshold;
  324. this.options.bounceEasing = typeof this.options.bounceEasing == 'string' ? utils.ease[this.options.bounceEasing] || utils.ease.circular : this.options.bounceEasing;
  325. this.options.resizePolling = this.options.resizePolling === undefined ? 60 : this.options.resizePolling;
  326. if ( this.options.tap === true ) {
  327. this.options.tap = 'tap';
  328. }
  329. // https://github.com/cubiq/iscrollForIosSelect/issues/1029
  330. if (!this.options.useTransition && !this.options.useTransform) {
  331. if(!(/relative|absolute/i).test(this.scrollerStyle.position)) {
  332. this.scrollerStyle.position = "relative";
  333. }
  334. }
  335. if ( this.options.shrinkScrollbars == 'scale' ) {
  336. this.options.useTransition = false;
  337. }
  338. this.options.invertWheelDirection = this.options.invertWheelDirection ? -1 : 1;
  339. if ( this.options.probeType == 3 ) {
  340. this.options.useTransition = false; }
  341. this.x = 0;
  342. this.y = 0;
  343. this.directionX = 0;
  344. this.directionY = 0;
  345. this._events = {};
  346. this._init();
  347. this.refresh();
  348. this.scrollTo(this.options.startX, this.options.startY);
  349. this.enable();
  350. }
  351. IScrollForIosSelect.prototype = {
  352. version: '1.0.0',
  353. _init: function () {
  354. this._initEvents();
  355. },
  356. destroy: function () {
  357. this._initEvents(true);
  358. clearTimeout(this.resizeTimeout);
  359. this.resizeTimeout = null;
  360. this._execEvent('destroy');
  361. },
  362. _transitionEnd: function (e) {
  363. if ( e.target != this.scroller || !this.isInTransition ) {
  364. return;
  365. }
  366. this._transitionTime();
  367. if ( !this.resetPosition(this.options.bounceTime) ) {
  368. this.isInTransition = false;
  369. this._execEvent('scrollEnd');
  370. }
  371. },
  372. _start: function (e) {
  373. // React to left mouse button only
  374. if ( utils.eventType[e.type] != 1 ) {
  375. // for button property
  376. // http://unixpapa.com/js/mouse.html
  377. var button;
  378. if (!e.which) {
  379. /* IE case */
  380. button = (e.button < 2) ? 0 :
  381. ((e.button == 4) ? 1 : 2);
  382. } else {
  383. /* All others */
  384. button = e.button;
  385. }
  386. if ( button !== 0 ) {
  387. return;
  388. }
  389. }
  390. if ( !this.enabled || (this.initiated && utils.eventType[e.type] !== this.initiated) ) {
  391. return;
  392. }
  393. if ( this.options.preventDefault && !utils.isBadAndroid && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) {
  394. e.preventDefault();
  395. }
  396. var point = e.touches ? e.touches[0] : e,
  397. pos;
  398. this.initiated = utils.eventType[e.type];
  399. this.moved = false;
  400. this.distX = 0;
  401. this.distY = 0;
  402. this.directionX = 0;
  403. this.directionY = 0;
  404. this.directionLocked = 0;
  405. this.startTime = utils.getTime();
  406. if ( this.options.useTransition && this.isInTransition ) {
  407. this._transitionTime();
  408. this.isInTransition = false;
  409. pos = this.getComputedPosition();
  410. this._translate(Math.round(pos.x), Math.round(pos.y));
  411. this._execEvent('scrollEnd');
  412. } else if ( !this.options.useTransition && this.isAnimating ) {
  413. this.isAnimating = false;
  414. this._execEvent('scrollEnd');
  415. }
  416. this.startX = this.x;
  417. this.startY = this.y;
  418. this.absStartX = this.x;
  419. this.absStartY = this.y;
  420. this.pointX = point.pageX;
  421. this.pointY = point.pageY;
  422. this._execEvent('beforeScrollStart');
  423. },
  424. _move: function (e) {
  425. if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) {
  426. return;
  427. }
  428. if ( this.options.preventDefault ) { // increases performance on Android? TODO: check!
  429. // e.preventDefault();
  430. }
  431. var point = e.touches ? e.touches[0] : e,
  432. deltaX = point.pageX - this.pointX,
  433. deltaY = point.pageY - this.pointY,
  434. timestamp = utils.getTime(),
  435. newX, newY,
  436. absDistX, absDistY;
  437. this.pointX = point.pageX;
  438. this.pointY = point.pageY;
  439. this.distX += deltaX;
  440. this.distY += deltaY;
  441. absDistX = Math.abs(this.distX);
  442. absDistY = Math.abs(this.distY);
  443. // We need to move at least 10 pixels for the scrolling to initiate
  444. if ( timestamp - this.endTime > 300 && (absDistX < 10 && absDistY < 10) ) {
  445. return;
  446. }
  447. // If you are scrolling in one direction lock the other
  448. if ( !this.directionLocked && !this.options.freeScroll ) {
  449. if ( absDistX > absDistY + this.options.directionLockThreshold ) {
  450. this.directionLocked = 'h'; // lock horizontally
  451. } else if ( absDistY >= absDistX + this.options.directionLockThreshold ) {
  452. this.directionLocked = 'v'; // lock vertically
  453. } else {
  454. this.directionLocked = 'n'; // no lock
  455. }
  456. }
  457. if ( this.directionLocked == 'h' ) {
  458. if ( this.options.eventPassthrough == 'vertical' ) {
  459. e.preventDefault();
  460. } else if ( this.options.eventPassthrough == 'horizontal' ) {
  461. this.initiated = false;
  462. return;
  463. }
  464. deltaY = 0;
  465. } else if ( this.directionLocked == 'v' ) {
  466. if ( this.options.eventPassthrough == 'horizontal' ) {
  467. e.preventDefault();
  468. } else if ( this.options.eventPassthrough == 'vertical' ) {
  469. this.initiated = false;
  470. return;
  471. }
  472. deltaX = 0;
  473. }
  474. deltaX = this.hasHorizontalScroll ? deltaX : 0;
  475. deltaY = this.hasVerticalScroll ? deltaY : 0;
  476. newX = this.x + deltaX;
  477. newY = this.y + deltaY;
  478. // Slow down if outside of the boundaries
  479. if ( newX > 0 || newX < this.maxScrollX ) {
  480. newX = this.options.bounce ? this.x + deltaX / 3 : newX > 0 ? 0 : this.maxScrollX;
  481. }
  482. if ( newY > 0 || newY < this.maxScrollY ) {
  483. newY = this.options.bounce ? this.y + deltaY / 3 : newY > 0 ? 0 : this.maxScrollY;
  484. }
  485. this.directionX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
  486. this.directionY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
  487. if ( !this.moved ) {
  488. this._execEvent('scrollStart');
  489. }
  490. this.moved = true;
  491. this._translate(newX, newY);
  492. if ( timestamp - this.startTime > 300 ) {
  493. this.startTime = timestamp;
  494. this.startX = this.x;
  495. this.startY = this.y;
  496. if ( this.options.probeType == 1 ) {
  497. this._execEvent('scroll');
  498. }
  499. }
  500. if ( this.options.probeType > 1 ) {
  501. this._execEvent('scroll');
  502. }
  503. },
  504. _end: function (e) {
  505. if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) {
  506. return;
  507. }
  508. if ( this.options.preventDefault && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) {
  509. e.preventDefault();
  510. }
  511. var point = e.changedTouches ? e.changedTouches[0] : e,
  512. momentumX,
  513. momentumY,
  514. duration = utils.getTime() - this.startTime,
  515. newX = Math.round(this.x),
  516. newY = Math.round(this.y),
  517. distanceX = Math.abs(newX - this.startX),
  518. distanceY = Math.abs(newY - this.startY),
  519. time = 0,
  520. easing = '';
  521. this.isInTransition = 0;
  522. this.initiated = 0;
  523. this.endTime = utils.getTime();
  524. // reset if we are outside of the boundaries
  525. if ( this.resetPosition(this.options.bounceTime) ) {
  526. return;
  527. }
  528. this.scrollTo(newX, newY); // ensures that the last position is rounded
  529. // we scrolled less than 10 pixels
  530. if ( !this.moved ) {
  531. if ( this.options.tap ) {
  532. utils.tap(e, this.options.tap);
  533. }
  534. if ( this.options.click ) {
  535. utils.click(e);
  536. }
  537. this._execEvent('scrollCancel');
  538. return;
  539. }
  540. if ( this._events.flick && duration < 200 && distanceX < 100 && distanceY < 100 ) {
  541. this._execEvent('flick');
  542. return;
  543. }
  544. // start momentum animation if needed
  545. if ( this.options.momentum && duration < 300 ) {
  546. momentumX = this.hasHorizontalScroll ? utils.momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0, this.options.deceleration) : { destination: newX, duration: 0 };
  547. momentumY = this.hasVerticalScroll ? utils.momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0, this.options.deceleration) : { destination: newY, duration: 0 };
  548. newX = momentumX.destination;
  549. newY = momentumY.destination;
  550. time = Math.max(momentumX.duration, momentumY.duration);
  551. this.isInTransition = 1;
  552. }
  553. if ( this.options.snap ) {
  554. var snap = this._nearestSnap(newX, newY);
  555. this.currentPage = snap;
  556. time = this.options.snapSpeed || Math.max(
  557. Math.max(
  558. Math.min(Math.abs(newX - snap.x), 1000),
  559. Math.min(Math.abs(newY - snap.y), 1000)
  560. ), 300);
  561. newX = snap.x;
  562. newY = snap.y;
  563. this.directionX = 0;
  564. this.directionY = 0;
  565. easing = this.options.bounceEasing;
  566. }
  567. if ( newX != this.x || newY != this.y ) {
  568. // change easing function when scroller goes out of the boundaries
  569. if ( newX > 0 || newX < this.maxScrollX || newY > 0 || newY < this.maxScrollY ) {
  570. easing = utils.ease.quadratic;
  571. }
  572. this.scrollTo(newX, newY, time, easing);
  573. return;
  574. }
  575. this._execEvent('scrollEnd');
  576. },
  577. _resize: function () {
  578. var that = this;
  579. clearTimeout(this.resizeTimeout);
  580. this.resizeTimeout = setTimeout(function () {
  581. that.refresh();
  582. }, this.options.resizePolling);
  583. },
  584. resetPosition: function (time) {
  585. var x = this.x,
  586. y = this.y;
  587. time = time || 0;
  588. if ( !this.hasHorizontalScroll || this.x > 0 ) {
  589. x = 0;
  590. } else if ( this.x < this.maxScrollX ) {
  591. x = this.maxScrollX;
  592. }
  593. if ( !this.hasVerticalScroll || this.y > 0 ) {
  594. y = 0;
  595. } else if ( this.y < this.maxScrollY ) {
  596. y = this.maxScrollY;
  597. }
  598. if ( x == this.x && y == this.y ) {
  599. return false;
  600. }
  601. this.scrollTo(x, y, time, this.options.bounceEasing);
  602. return true;
  603. },
  604. disable: function () {
  605. this.enabled = false;
  606. },
  607. enable: function () {
  608. this.enabled = true;
  609. },
  610. refresh: function () {
  611. var rf = this.wrapper.offsetHeight; // Force reflow
  612. this.wrapperWidth = this.wrapper.clientWidth;
  613. this.wrapperHeight = this.wrapper.clientHeight;
  614. this.scrollerWidth = this.scroller.offsetWidth;
  615. this.scrollerHeight = this.scroller.offsetHeight;
  616. this.maxScrollX = this.wrapperWidth - this.scrollerWidth;
  617. this.maxScrollY = this.wrapperHeight - this.scrollerHeight;
  618. this.hasHorizontalScroll = this.options.scrollX && this.maxScrollX < 0;
  619. this.hasVerticalScroll = this.options.scrollY && this.maxScrollY < 0;
  620. if ( !this.hasHorizontalScroll ) {
  621. this.maxScrollX = 0;
  622. this.scrollerWidth = this.wrapperWidth;
  623. }
  624. if ( !this.hasVerticalScroll ) {
  625. this.maxScrollY = 0;
  626. this.scrollerHeight = this.wrapperHeight;
  627. }
  628. this.endTime = 0;
  629. this.directionX = 0;
  630. this.directionY = 0;
  631. this.wrapperOffset = utils.offset(this.wrapper);
  632. this._execEvent('refresh');
  633. this.resetPosition();
  634. },
  635. on: function (type, fn) {
  636. if ( !this._events[type] ) {
  637. this._events[type] = [];
  638. }
  639. this._events[type].push(fn);
  640. },
  641. off: function (type, fn) {
  642. if ( !this._events[type] ) {
  643. return;
  644. }
  645. var index = this._events[type].indexOf(fn);
  646. if ( index > -1 ) {
  647. this._events[type].splice(index, 1);
  648. }
  649. },
  650. _execEvent: function (type) {
  651. if ( !this._events[type] ) {
  652. return;
  653. }
  654. var i = 0,
  655. l = this._events[type].length;
  656. if ( !l ) {
  657. return;
  658. }
  659. for ( ; i < l; i++ ) {
  660. this._events[type][i].apply(this, [].slice.call(arguments, 1));
  661. }
  662. },
  663. scrollTo: function (x, y, time, easing) {
  664. easing = easing || utils.ease.circular;
  665. this.isInTransition = this.options.useTransition && time > 0;
  666. var transitionType = this.options.useTransition && easing.style;
  667. if ( !time || transitionType ) {
  668. if(transitionType) {
  669. this._transitionTimingFunction(easing.style);
  670. this._transitionTime(time);
  671. }
  672. this._translate(x, y);
  673. } else {
  674. this._animate(x, y, time, easing.fn);
  675. }
  676. },
  677. scrollToElement: function (el, time, offsetX, offsetY, easing) {
  678. el = el.nodeType ? el : this.scroller.querySelector(el);
  679. if ( !el ) {
  680. return;
  681. }
  682. var pos = utils.offset(el);
  683. pos.left -= this.wrapperOffset.left;
  684. pos.top -= this.wrapperOffset.top;
  685. // if offsetX/Y are true we center the element to the screen
  686. if ( offsetX === true ) {
  687. offsetX = Math.round(el.offsetWidth / 2 - this.wrapper.offsetWidth / 2);
  688. }
  689. if ( offsetY === true ) {
  690. offsetY = Math.round(el.offsetHeight / 2 - this.wrapper.offsetHeight / 2);
  691. }
  692. pos.left -= offsetX || 0;
  693. pos.top -= offsetY || 0;
  694. pos.left = pos.left > 0 ? 0 : pos.left < this.maxScrollX ? this.maxScrollX : pos.left;
  695. pos.top = pos.top > 0 ? 0 : pos.top < this.maxScrollY ? this.maxScrollY : pos.top;
  696. time = time === undefined || time === null || time === 'auto' ? Math.max(Math.abs(this.x-pos.left), Math.abs(this.y-pos.top)) : time;
  697. this.scrollTo(pos.left, pos.top, time, easing);
  698. },
  699. _transitionTime: function (time) {
  700. if (!this.options.useTransition) {
  701. return;
  702. }
  703. time = time || 0;
  704. var durationProp = utils.style.transitionDuration;
  705. if(!durationProp) {
  706. return;
  707. }
  708. this.scrollerStyle[durationProp] = time + 'ms';
  709. if ( !time && utils.isBadAndroid ) {
  710. this.scrollerStyle[durationProp] = '0.0001ms';
  711. // remove 0.0001ms
  712. var self = this;
  713. rAF(function() {
  714. if(self.scrollerStyle[durationProp] === '0.0001ms') {
  715. self.scrollerStyle[durationProp] = '0s';
  716. }
  717. });
  718. }
  719. },
  720. _transitionTimingFunction: function (easing) {
  721. this.scrollerStyle[utils.style.transitionTimingFunction] = easing;
  722. },
  723. _translate: function (x, y) {
  724. if ( this.options.useTransform ) {
  725. this.scrollerStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.translateZ;
  726. } else {
  727. x = Math.round(x);
  728. y = Math.round(y);
  729. this.scrollerStyle.left = x + 'px';
  730. this.scrollerStyle.top = y + 'px';
  731. }
  732. this.x = x;
  733. this.y = y;
  734. },
  735. _initEvents: function (remove) {
  736. var eventType = remove ? utils.removeEvent : utils.addEvent,
  737. target = this.options.bindToWrapper ? this.wrapper : window;
  738. eventType(window, 'orientationchange', this);
  739. eventType(window, 'resize', this);
  740. if ( this.options.click ) {
  741. eventType(this.wrapper, 'click', this, true);
  742. }
  743. if ( !this.options.disableMouse ) {
  744. eventType(this.wrapper, 'mousedown', this);
  745. eventType(target, 'mousemove', this);
  746. eventType(target, 'mousecancel', this);
  747. eventType(target, 'mouseup', this);
  748. }
  749. if ( utils.hasPointer && !this.options.disablePointer ) {
  750. eventType(this.wrapper, utils.prefixPointerEvent('pointerdown'), this);
  751. eventType(target, utils.prefixPointerEvent('pointermove'), this);
  752. eventType(target, utils.prefixPointerEvent('pointercancel'), this);
  753. eventType(target, utils.prefixPointerEvent('pointerup'), this);
  754. }
  755. if ( utils.hasTouch && !this.options.disableTouch ) {
  756. eventType(this.wrapper, 'touchstart', this);
  757. eventType(target, 'touchmove', this);
  758. eventType(target, 'touchcancel', this);
  759. eventType(target, 'touchend', this);
  760. }
  761. eventType(this.scroller, 'transitionend', this);
  762. eventType(this.scroller, 'webkitTransitionEnd', this);
  763. eventType(this.scroller, 'oTransitionEnd', this);
  764. eventType(this.scroller, 'MSTransitionEnd', this);
  765. },
  766. getComputedPosition: function () {
  767. var matrix = window.getComputedStyle(this.scroller, null),
  768. x, y;
  769. if ( this.options.useTransform ) {
  770. matrix = matrix[utils.style.transform].split(')')[0].split(', ');
  771. x = +(matrix[12] || matrix[4]);
  772. y = +(matrix[13] || matrix[5]);
  773. } else {
  774. x = +matrix.left.replace(/[^-\d.]/g, '');
  775. y = +matrix.top.replace(/[^-\d.]/g, '');
  776. }
  777. return { x: x, y: y };
  778. },
  779. _animate: function (destX, destY, duration, easingFn) {
  780. var that = this,
  781. startX = this.x,
  782. startY = this.y,
  783. startTime = utils.getTime(),
  784. destTime = startTime + duration;
  785. function step () {
  786. var now = utils.getTime(),
  787. newX, newY,
  788. easing;
  789. if ( now >= destTime ) {
  790. that.isAnimating = false;
  791. that._translate(destX, destY);
  792. if ( !that.resetPosition(that.options.bounceTime) ) {
  793. that._execEvent('scrollEnd');
  794. }
  795. return;
  796. }
  797. now = ( now - startTime ) / duration;
  798. easing = easingFn(now);
  799. newX = ( destX - startX ) * easing + startX;
  800. newY = ( destY - startY ) * easing + startY;
  801. that._translate(newX, newY);
  802. if ( that.isAnimating ) {
  803. rAF(step);
  804. }
  805. if ( that.options.probeType == 3 ) {
  806. that._execEvent('scroll');
  807. }
  808. }
  809. this.isAnimating = true;
  810. step();
  811. },
  812. handleEvent: function (e) {
  813. switch ( e.type ) {
  814. case 'touchstart':
  815. case 'pointerdown':
  816. case 'MSPointerDown':
  817. case 'mousedown':
  818. this._start(e);
  819. break;
  820. case 'touchmove':
  821. case 'pointermove':
  822. case 'MSPointerMove':
  823. case 'mousemove':
  824. this._move(e);
  825. break;
  826. case 'touchend':
  827. case 'pointerup':
  828. case 'MSPointerUp':
  829. case 'mouseup':
  830. case 'touchcancel':
  831. case 'pointercancel':
  832. case 'MSPointerCancel':
  833. case 'mousecancel':
  834. this._end(e);
  835. break;
  836. case 'orientationchange':
  837. case 'resize':
  838. this._resize();
  839. break;
  840. case 'transitionend':
  841. case 'webkitTransitionEnd':
  842. case 'oTransitionEnd':
  843. case 'MSTransitionEnd':
  844. this._transitionEnd(e);
  845. break;
  846. case 'click':
  847. if ( this.enabled && !e._constructed ) {
  848. e.preventDefault();
  849. e.stopPropagation();
  850. }
  851. break;
  852. }
  853. }
  854. };
  855. IScrollForIosSelect.utils = utils;
  856. var iosSelectUtil = {
  857. isArray: function (arg1) {
  858. return Object.prototype.toString.call(arg1) === '[object Array]';
  859. },
  860. isFunction: function (arg1) {
  861. return typeof arg1 === 'function';
  862. },
  863. attrToData: function (dom, index) {
  864. var obj = {};
  865. for (var p in dom.dataset) {
  866. obj[p] = dom.dataset[p];
  867. }
  868. obj['dom'] = dom;
  869. obj['atindex'] = index;
  870. return obj;
  871. },
  872. attrToHtml: function (obj) {
  873. var html = '';
  874. for (var p in obj) {
  875. html += 'data-' + p + '="' + obj[p] + '"';
  876. }
  877. return html;
  878. }
  879. };
  880. /*function preventEventFun(e) {
  881. e.preventDefault();
  882. }*/
  883. // Layer
  884. function Layer(html, opts) {
  885. if (!(this instanceof Layer)) {
  886. return new Layer(html, opts);
  887. }
  888. this.html = html;
  889. this.opts = opts;
  890. var el = document.createElement('div');
  891. el.className = 'olay';
  892. var layer_el = document.createElement('div');
  893. layer_el.className = 'layer';
  894. this.el = el;
  895. this.layer_el = layer_el;
  896. this.init();
  897. }
  898. Layer.prototype = {
  899. init: function () {
  900. this.layer_el.innerHTML = this.html;
  901. if (this.opts.container && document.querySelector(this.opts.container)) {
  902. document.querySelector(this.opts.container).appendChild(this.el);
  903. }
  904. else {
  905. document.body.appendChild(this.el);
  906. }
  907. this.el.appendChild(this.layer_el);
  908. this.el.style.height = Math.max(document.documentElement.getBoundingClientRect().height, window.innerHeight);
  909. if (this.opts.className) {
  910. this.el.className += ' ' + this.opts.className;
  911. }
  912. this.bindEvent();
  913. },
  914. bindEvent: function () {
  915. var sureDom = this.el.querySelectorAll('.sure');
  916. var closeDom = this.el.querySelectorAll('.close');
  917. var self = this;
  918. this.el.addEventListener('click', function(e) {
  919. self.close();
  920. self.opts.maskCallback && self.opts.maskCallback();
  921. });
  922. this.layer_el.addEventListener('click', function(e) {
  923. e.stopPropagation();
  924. });
  925. Array.prototype.slice.call(sureDom).forEach(function (item, index) {
  926. item.addEventListener('click', function () {
  927. self.close();
  928. });
  929. });
  930. Array.prototype.slice.call(closeDom).forEach(function (item, index) {
  931. item.addEventListener('click', function () {
  932. self.close();
  933. self.opts.fallback && self.opts.fallback();
  934. });
  935. });
  936. },
  937. close: function () {
  938. var self=this;
  939. if (self.el) {
  940. if (self.opts.showAnimate) {
  941. self.el.className += ' fadeOutDown';
  942. self.el.addEventListener(aF, function () {
  943. self.removeDom();
  944. });
  945. }
  946. else {
  947. self.removeDom();
  948. }
  949. }
  950. },
  951. removeDom: function (){
  952. this.el.parentNode.removeChild(this.el);
  953. this.el = null;
  954. if (document.documentElement.classList.contains('ios-select-body-class')) {
  955. document.documentElement.classList.remove('ios-select-body-class');
  956. /*document.body.removeEventListener('touchmove', preventEventFun, {
  957. passive: false
  958. });*/
  959. }
  960. }
  961. }
  962. function IosSelect(level, data, options) {
  963. if (!iosSelectUtil.isArray(data) || data.length === 0) {
  964. throw new TypeError('the data must be a non-empty array!');
  965. return;
  966. }
  967. if ([1, 2, 3, 4, 5, 6].indexOf(level) == -1) {
  968. throw new RangeError('the level parameter must be one of 1,2,3,4,5,6!');
  969. return;
  970. }
  971. this.data = data;
  972. this.level = level || 1;
  973. this.options = options;
  974. this.typeBox = 'one-level-box';
  975. var boxClass = ['one', 'two', 'three', 'four', 'five', 'six'];
  976. if (this.level <= 6 && this.level >= 1) {
  977. this.typeBox = boxClass[parseInt(this.level) - 1] + '-level-box';
  978. }
  979. this.title = options.title || '';
  980. this.options.itemHeight = options.itemHeight || 35;
  981. this.options.itemShowCount = [3, 5, 7, 9].indexOf(options.itemShowCount) !== -1? options.itemShowCount: 7;
  982. this.options.coverArea1Top = Math.floor(this.options.itemShowCount / 2);
  983. this.options.coverArea2Top = Math.ceil(this.options.itemShowCount / 2);
  984. this.options.headerHeight = options.headerHeight || 44;
  985. this.options.relation = iosSelectUtil.isArray(this.options.relation)? this.options.relation: [];
  986. this.options.oneTwoRelation = this.options.relation[0];
  987. this.options.twoThreeRelation = this.options.relation[1];
  988. this.options.threeFourRelation = this.options.relation[2];
  989. this.options.fourFiveRelation = this.options.relation[3];
  990. this.options.fiveSixRelation = this.options.relation[4];
  991. if (this.options.cssUnit !== 'px' && this.options.cssUnit !== 'rem') {
  992. this.options.cssUnit = 'px';
  993. }
  994. var self = this;
  995. // 选中元素的信息
  996. this.selectOneObj = {
  997. id: self.options.oneLevelId
  998. };
  999. this.selectTwoObj = {
  1000. id: self.options.twoLevelId
  1001. };
  1002. this.selectThreeObj = {
  1003. id: self.options.threeLevelId
  1004. };
  1005. this.selectFourObj = {
  1006. id: self.options.fourLevelId
  1007. };
  1008. this.selectFiveObj = {
  1009. id: self.options.fiveLevelId
  1010. };
  1011. this.selectSixObj = {
  1012. id: self.options.sixLevelId
  1013. };
  1014. this.setBase();
  1015. this.init();
  1016. };
  1017. IosSelect.prototype = {
  1018. init: function () {
  1019. this.initLayer();
  1020. this.setLevelData(1, this.options.oneLevelId, this.options.twoLevelId, this.options.threeLevelId, this.options.fourLevelId, this.options.fiveLevelId, this.options.sixLevelId);
  1021. },
  1022. initLayer: function () {
  1023. var self = this;
  1024. var sureText = this.options.sureText || '确定';
  1025. var closeText = this.options.closeText || '取消';
  1026. var headerHeightCss = this.options.headerHeight + this.options.cssUnit;
  1027. var all_html = [
  1028. '<header style="height: ' + headerHeightCss + '; line-height: ' + headerHeightCss + '" class="iosselect-header">',
  1029. '<a style="height: ' + headerHeightCss + '; line-height: ' + headerHeightCss + '" href="javascript:void(0)" class="close">' + closeText + '</a>',
  1030. '<a style="height: ' + headerHeightCss + '; line-height: ' + headerHeightCss + '" href="javascript:void(0)" class="sure">' + sureText + '</a>',
  1031. '<h2 id="iosSelectTitle"></h2>',
  1032. '</header>',
  1033. '<section class="iosselect-box">',
  1034. '<div class="one-level-contain" id="oneLevelContain">',
  1035. '<ul class="select-one-level">',
  1036. '</ul>',
  1037. '</div>',
  1038. '<div class="two-level-contain" id="twoLevelContain">',
  1039. '<ul class="select-two-level">',
  1040. '</ul>',
  1041. '</div>',
  1042. '<div class="three-level-contain" id="threeLevelContain">',
  1043. '<ul class="select-three-level">',
  1044. '</ul>',
  1045. '</div>',
  1046. '<div class="four-level-contain" id="fourLevelContain">',
  1047. '<ul class="select-four-level">',
  1048. '</ul>',
  1049. '</div>',
  1050. '<div class="five-level-contain" id="fiveLevelContain">',
  1051. '<ul class="select-five-level">',
  1052. '</ul>',
  1053. '</div>',
  1054. '<div class="six-level-contain" id="sixLevelContain">',
  1055. '<ul class="select-six-level">',
  1056. '</ul>',
  1057. '</div>',
  1058. '</section>',
  1059. '<hr class="cover-area1"/>',
  1060. '<hr class="cover-area2"/>',
  1061. '<div class="ios-select-loading-box" id="iosSelectLoadingBox">',
  1062. '<div class="ios-select-loading"></div>',
  1063. '</div>'
  1064. ].join('\r\n');
  1065. this.iosSelectLayer = new Layer(all_html, {
  1066. className: 'ios-select-widget-box ' + this.typeBox + (this.options.addClassName? ' ' + this.options.addClassName: '') + (this.options.showAnimate? ' fadeInUp': ''),
  1067. container: this.options.container || '',
  1068. showAnimate: this.options.showAnimate,
  1069. fallback: this.options.fallback,
  1070. maskCallback: this.options.maskCallback
  1071. });
  1072. this.iosSelectTitleDom = this.iosSelectLayer.el.querySelector('#iosSelectTitle');
  1073. this.iosSelectLoadingBoxDom = this.iosSelectLayer.el.querySelector('#iosSelectLoadingBox');
  1074. this.iosSelectTitleDom.innerHTML = this.title;
  1075. if (this.options.headerHeight && this.options.itemHeight) {
  1076. this.coverArea1Dom = this.iosSelectLayer.el.querySelector('.cover-area1');
  1077. this.coverArea1Dom.style.top = this.options.headerHeight + this.options.itemHeight * this.options.coverArea1Top + this.options.cssUnit;
  1078. this.coverArea2Dom = this.iosSelectLayer.el.querySelector('.cover-area2');
  1079. this.coverArea2Dom.style.top = this.options.headerHeight + this.options.itemHeight * this.options.coverArea2Top + this.options.cssUnit;
  1080. }
  1081. this.oneLevelContainDom = this.iosSelectLayer.el.querySelector('#oneLevelContain');
  1082. this.twoLevelContainDom = this.iosSelectLayer.el.querySelector('#twoLevelContain');
  1083. this.threeLevelContainDom = this.iosSelectLayer.el.querySelector('#threeLevelContain');
  1084. this.fourLevelContainDom = this.iosSelectLayer.el.querySelector('#fourLevelContain');
  1085. this.fiveLevelContainDom = this.iosSelectLayer.el.querySelector('#fiveLevelContain');
  1086. this.sixLevelContainDom = this.iosSelectLayer.el.querySelector('#sixLevelContain');
  1087. this.oneLevelUlContainDom = this.iosSelectLayer.el.querySelector('.select-one-level');
  1088. this.twoLevelUlContainDom = this.iosSelectLayer.el.querySelector('.select-two-level');
  1089. this.threeLevelUlContainDom = this.iosSelectLayer.el.querySelector('.select-three-level');
  1090. this.fourLevelUlContainDom = this.iosSelectLayer.el.querySelector('.select-four-level');
  1091. this.fiveLevelUlContainDom = this.iosSelectLayer.el.querySelector('.select-five-level');
  1092. this.sixLevelUlContainDom = this.iosSelectLayer.el.querySelector('.select-six-level');
  1093. this.iosSelectLayer.el.querySelector('.layer').style.height = this.options.itemHeight * this.options.itemShowCount + this.options.headerHeight + this.options.cssUnit;
  1094. this.oneLevelContainDom.style.height = this.options.itemHeight * this.options.itemShowCount + this.options.cssUnit;
  1095. document.documentElement.classList.add('ios-select-body-class');
  1096. /*document.body.addEventListener('touchmove', preventEventFun, {
  1097. passive: false
  1098. });*/
  1099. this.scrollOne = new IScrollForIosSelect('#oneLevelContain', {
  1100. probeType: 3,
  1101. bounce: false
  1102. });
  1103. this.setScorllEvent(this.scrollOne, 1);
  1104. if (this.level >= 2) {
  1105. this.twoLevelContainDom.style.height = this.options.itemHeight * this.options.itemShowCount + this.options.cssUnit;
  1106. this.scrollTwo = new IScrollForIosSelect('#twoLevelContain', {
  1107. probeType: 3,
  1108. bounce: false
  1109. });
  1110. this.setScorllEvent(this.scrollTwo, 2);
  1111. }
  1112. if (this.level >= 3) {
  1113. this.threeLevelContainDom.style.height = this.options.itemHeight * this.options.itemShowCount + this.options.cssUnit;
  1114. this.scrollThree = new IScrollForIosSelect('#threeLevelContain', {
  1115. probeType: 3,
  1116. bounce: false
  1117. });
  1118. this.setScorllEvent(this.scrollThree, 3);
  1119. }
  1120. if (this.level >= 4) {
  1121. this.fourLevelContainDom.style.height = this.options.itemHeight * this.options.itemShowCount + this.options.cssUnit;
  1122. this.scrollFour = new IScrollForIosSelect('#fourLevelContain', {
  1123. probeType: 3,
  1124. bounce: false
  1125. });
  1126. this.setScorllEvent(this.scrollFour, 4);
  1127. }
  1128. if (this.level >= 5) {
  1129. this.fiveLevelContainDom.style.height = this.options.itemHeight * this.options.itemShowCount + this.options.cssUnit;
  1130. this.scrollFive = new IScrollForIosSelect('#fiveLevelContain', {
  1131. probeType: 3,
  1132. bounce: false
  1133. });
  1134. this.setScorllEvent(this.scrollFive, 5);
  1135. }
  1136. if (this.level >= 6) {
  1137. this.sixLevelContainDom.style.height = this.options.itemHeight * this.options.itemShowCount + this.options.cssUnit;
  1138. this.scrollSix = new IScrollForIosSelect('#sixLevelContain', {
  1139. probeType: 3,
  1140. bounce: false
  1141. });
  1142. this.setScorllEvent(this.scrollSix, 6);
  1143. }
  1144. // 确认
  1145. this.selectBtnDom = this.iosSelectLayer.el.querySelector('.sure');
  1146. this.selectBtnDom.addEventListener('click', function (e) {
  1147. self.options.callback && self.options.callback(self.selectOneObj, self.selectTwoObj, self.selectThreeObj, self.selectFourObj, self.selectFiveObj, self.selectSixObj);
  1148. });
  1149. },
  1150. mapKeyByIndex: function (index) {
  1151. var self = this;
  1152. var map = {
  1153. index: 1,
  1154. levelContain: self.oneLevelContainDom,
  1155. relation: self.options.oneTwoRelation
  1156. };
  1157. if (index === 2) {
  1158. map = {
  1159. index: 2,
  1160. levelContain: self.twoLevelContainDom,
  1161. relation: self.options.twoThreeRelation
  1162. };
  1163. }
  1164. else if (index === 3) {
  1165. map = {
  1166. index: 3,
  1167. levelContain: self.threeLevelContainDom,
  1168. relation: self.options.threeFourRelation
  1169. };
  1170. }
  1171. else if (index === 4) {
  1172. map = {
  1173. index: 4,
  1174. levelContain: self.fourLevelContainDom,
  1175. relation: self.options.fourFiveRelation
  1176. };
  1177. }
  1178. else if (index === 5) {
  1179. map = {
  1180. index: 5,
  1181. levelContain: self.fiveLevelContainDom,
  1182. relation: self.options.fiveSixRelation
  1183. };
  1184. }
  1185. else if (index === 6) {
  1186. map = {
  1187. index: 6,
  1188. levelContain: self.sixLevelContainDom,
  1189. relation: 0
  1190. };
  1191. }
  1192. return map;
  1193. },
  1194. setScorllEvent: function (scrollInstance, index) {
  1195. var self = this;
  1196. var mapKey = self.mapKeyByIndex(index);
  1197. scrollInstance.on('scrollStart', function () {
  1198. self.toggleClassList(mapKey.levelContain);
  1199. });
  1200. scrollInstance.on('scroll', function () {
  1201. if (isNaN(this.y)) {
  1202. return;
  1203. }
  1204. var pa = Math.abs(this.y / self.baseSize) / self.options.itemHeight;
  1205. var plast = 1;
  1206. plast = Math.round(pa) + 1;
  1207. self.toggleClassList(mapKey.levelContain);
  1208. self.changeClassName(mapKey.levelContain, plast);
  1209. });
  1210. scrollInstance.on('scrollEnd', function () {
  1211. var pa = Math.abs(this.y / self.baseSize) / self.options.itemHeight;
  1212. var plast = 1;
  1213. var to = 0;
  1214. if (Math.ceil(pa) === Math.round(pa)) {
  1215. to = Math.ceil(pa) * self.options.itemHeight * self.baseSize;
  1216. plast = Math.ceil(pa) + 1;
  1217. } else {
  1218. to = Math.floor(pa) * self.options.itemHeight * self.baseSize;
  1219. plast = Math.floor(pa) + 1;
  1220. }
  1221. scrollInstance.scrollTo(0, -to, 0);
  1222. self.toggleClassList(mapKey.levelContain);
  1223. var pdom = self.changeClassName(mapKey.levelContain, plast);
  1224. var obj = iosSelectUtil.attrToData(pdom, plast);
  1225. self.setSelectObj(index, obj);
  1226. if (self.level > index) {
  1227. if ((mapKey.relation === 1 && iosSelectUtil.isArray(self.data[index])) || iosSelectUtil.isFunction(self.data[index])) {
  1228. self.setLevelData(index + 1, self.selectOneObj.id, self.selectTwoObj.id, self.selectThreeObj.id, self.selectFourObj.id, self.selectFiveObj.id, self.selectSixObj.id);
  1229. }
  1230. }
  1231. self.options.scrollback && self.options.scrollback(self.selectOneObj, self.selectTwoObj, self.selectThreeObj, self.selectFourObj, self.selectFiveObj, self.selectSixObj);
  1232. });
  1233. scrollInstance.on('scrollCancel', function () {
  1234. var pa = Math.abs(this.y / self.baseSize) / self.options.itemHeight;
  1235. var plast = 1;
  1236. var to = 0;
  1237. if (Math.ceil(pa) === Math.round(pa)) {
  1238. to = Math.ceil(pa) * self.options.itemHeight * self.baseSize;
  1239. plast = Math.ceil(pa) + 1;
  1240. } else {
  1241. to = Math.floor(pa) * self.options.itemHeight * self.baseSize;
  1242. plast = Math.floor(pa) + 1;
  1243. }
  1244. scrollInstance.scrollTo(0, -to, 0);
  1245. self.toggleClassList(mapKey.levelContain);
  1246. var pdom = self.changeClassName(mapKey.levelContain, plast);
  1247. var obj = iosSelectUtil.attrToData(pdom, plast);
  1248. self.setSelectObj(index, obj);
  1249. if (self.level > index) {
  1250. if ((mapKey.relation === 1 && iosSelectUtil.isArray(self.data[index])) || iosSelectUtil.isFunction(self.data[index])) {
  1251. self.setLevelData(index + 1, self.selectOneObj.id, self.selectTwoObj.id, self.selectThreeObj.id, self.selectFourObj.id, self.selectFiveObj.id, self.selectSixObj.id);
  1252. }
  1253. }
  1254. });
  1255. },
  1256. loadingShow: function () {
  1257. this.options.showLoading && (this.iosSelectLoadingBoxDom.style.display = 'block');
  1258. },
  1259. loadingHide: function () {
  1260. this.iosSelectLoadingBoxDom.style.display = 'none';
  1261. },
  1262. mapRenderByIndex: function (index) {
  1263. var self = this;
  1264. var map = {
  1265. index: 1,
  1266. relation: 0,
  1267. levelUlContainDom: self.oneLevelUlContainDom,
  1268. scrollInstance: self.scrollOne,
  1269. levelContainDom: self.oneLevelContainDom
  1270. };
  1271. if (index === 2) {
  1272. map = {
  1273. index: 2,
  1274. relation: self.options.oneTwoRelation,
  1275. levelUlContainDom: self.twoLevelUlContainDom,
  1276. scrollInstance: self.scrollTwo,
  1277. levelContainDom: self.twoLevelContainDom
  1278. };
  1279. }
  1280. else if (index === 3) {
  1281. map = {
  1282. index: 3,
  1283. relation: self.options.twoThreeRelation,
  1284. levelUlContainDom: self.threeLevelUlContainDom,
  1285. scrollInstance: self.scrollThree,
  1286. levelContainDom: self.threeLevelContainDom
  1287. };
  1288. }
  1289. else if (index === 4) {
  1290. map = {
  1291. index: 4,
  1292. relation: self.options.threeFourRelation,
  1293. levelUlContainDom: self.fourLevelUlContainDom,
  1294. scrollInstance: self.scrollFour,
  1295. levelContainDom: self.fourLevelContainDom
  1296. };
  1297. }
  1298. else if (index === 5) {
  1299. map = {
  1300. index: 5,
  1301. relation: self.options.fourFiveRelation,
  1302. levelUlContainDom: self.fiveLevelUlContainDom,
  1303. scrollInstance: self.scrollFive,
  1304. levelContainDom: self.fiveLevelContainDom
  1305. };
  1306. }
  1307. else if (index === 6) {
  1308. map = {
  1309. index: 6,
  1310. relation: self.options.fiveSixRelation,
  1311. levelUlContainDom: self.sixLevelUlContainDom,
  1312. scrollInstance: self.scrollSix,
  1313. levelContainDom: self.sixLevelContainDom
  1314. };
  1315. }
  1316. return map;
  1317. },
  1318. getLevelData: function (index, oneLevelId, twoLevelId, threeLevelId, fourLevelId, fiveLevelId) {
  1319. var levelData = [];
  1320. var renderMap = this.mapRenderByIndex(index);
  1321. if (index === 1) {
  1322. levelData = this.data[0];
  1323. }
  1324. else if (renderMap.relation === 1) {
  1325. var pid = arguments[index - 1];
  1326. this.data[index - 1].forEach(function (v, i, o) {
  1327. if (v['parentId'] == pid) {
  1328. levelData.push(v);
  1329. }
  1330. });
  1331. }
  1332. else {
  1333. levelData = this.data[index - 1];
  1334. }
  1335. return levelData;
  1336. },
  1337. setLevelData: function (index, oneLevelId, twoLevelId, threeLevelId, fourLevelId, fiveLevelId, sixLevelId) {
  1338. if (iosSelectUtil.isArray(this.data[index - 1])) {
  1339. var levelData = this.getLevelData(index, oneLevelId, twoLevelId, threeLevelId, fourLevelId);
  1340. this.renderLevel(index, oneLevelId, twoLevelId, threeLevelId, fourLevelId, fiveLevelId, sixLevelId, levelData);
  1341. }
  1342. else if (iosSelectUtil.isFunction(this.data[index - 1])) {
  1343. this.loadingShow();
  1344. this.data[index - 1].apply(this, [oneLevelId, twoLevelId, threeLevelId, fourLevelId, fiveLevelId].slice(0, index - 1).concat(function (levelData) {
  1345. this.loadingHide();
  1346. this.renderLevel(index, oneLevelId, twoLevelId, threeLevelId, fourLevelId, fiveLevelId, sixLevelId, levelData);
  1347. }.bind(this)));
  1348. }
  1349. else {
  1350. throw new Error('data format error');
  1351. }
  1352. },
  1353. renderLevel: function (index, oneLevelId, twoLevelId, threeLevelId, fourLevelId, fiveLevelId, sixLevelId, levelData) {
  1354. var plast = 0;
  1355. var curLevelId = arguments[index];
  1356. var hasAtId = levelData.some(function (v, i, o) {
  1357. return v.id == curLevelId;
  1358. });
  1359. if (!hasAtId) {
  1360. curLevelId = levelData[0]['id'];
  1361. }
  1362. var tmpHtml = '';
  1363. var itemHeightStyle = this.options.itemHeight + this.options.cssUnit;
  1364. tmpHtml += this.getWhiteItem();
  1365. levelData.forEach(function (v, i, o) {
  1366. if (v.id == curLevelId) {
  1367. tmpHtml += '<li style="height: ' + itemHeightStyle + '; line-height: ' + itemHeightStyle +';"' + iosSelectUtil.attrToHtml(v) + ' class="at">' + v.value + '</li>';
  1368. plast = i + 1;
  1369. }
  1370. else {
  1371. tmpHtml += '<li style="height: ' + itemHeightStyle + '; line-height: ' + itemHeightStyle +';"' + iosSelectUtil.attrToHtml(v) + '>' + v.value + '</li>';
  1372. }
  1373. });
  1374. tmpHtml += this.getWhiteItem();
  1375. var renderMap = this.mapRenderByIndex(index);
  1376. renderMap.levelUlContainDom.innerHTML = tmpHtml;
  1377. renderMap.scrollInstance.refresh();
  1378. renderMap.scrollInstance.scrollToElement(':nth-child(' + plast + ')', 0);
  1379. var pdom = this.changeClassName(renderMap.levelContainDom, plast);
  1380. var obj = iosSelectUtil.attrToData(pdom, plast);
  1381. this.setSelectObj(index, obj);
  1382. if (this.level > index) {
  1383. this.setLevelData(index + 1, this.selectOneObj.id, this.selectTwoObj.id, this.selectThreeObj.id, this.selectFourObj.id, this.selectFiveObj.id, this.selectSixObj.id);
  1384. }
  1385. },
  1386. setSelectObj: function (index, obj) {
  1387. if (index === 1) {
  1388. this.selectOneObj = obj;
  1389. }
  1390. else if (index === 2) {
  1391. this.selectTwoObj = obj;
  1392. }
  1393. else if (index === 3) {
  1394. this.selectThreeObj = obj;
  1395. }
  1396. else if (index === 4) {
  1397. this.selectFourObj = obj;
  1398. }
  1399. else if (index === 5) {
  1400. this.selectFiveObj = obj;
  1401. }
  1402. else if (index === 6) {
  1403. this.selectSixObj = obj;
  1404. }
  1405. },
  1406. getWhiteItem: function () {
  1407. var whiteItemHtml = '';
  1408. var itemHeightStyle = this.options.itemHeight + this.options.cssUnit;
  1409. var itemLi = '<li style="height: ' + itemHeightStyle + '; line-height: ' + itemHeightStyle + '"></li>';
  1410. whiteItemHtml += itemLi;
  1411. if (this.options.itemShowCount > 3) {
  1412. whiteItemHtml += itemLi;
  1413. }
  1414. if (this.options.itemShowCount > 5) {
  1415. whiteItemHtml += itemLi;
  1416. }
  1417. if (this.options.itemShowCount > 7) {
  1418. whiteItemHtml += itemLi;
  1419. }
  1420. return whiteItemHtml;
  1421. },
  1422. changeClassName: function (levelContainDom, plast) {
  1423. var pdom;
  1424. if (this.options.itemShowCount === 3) {
  1425. pdom = levelContainDom.querySelector('li:nth-child(' + (plast + 1) + ')');
  1426. pdom.classList.add('at');
  1427. }
  1428. else if (this.options.itemShowCount === 5) {
  1429. pdom = levelContainDom.querySelector('li:nth-child(' + (plast + 2) + ')');
  1430. pdom.classList.add('at');
  1431. levelContainDom.querySelector('li:nth-child(' + (plast + 1) + ')').classList.add('side1');
  1432. levelContainDom.querySelector('li:nth-child(' + (plast + 3) + ')').classList.add('side1');
  1433. }
  1434. else if (this.options.itemShowCount === 7) {
  1435. pdom = levelContainDom.querySelector('li:nth-child(' + (plast + 3) + ')');
  1436. pdom.classList.add('at');
  1437. levelContainDom.querySelector('li:nth-child(' + (plast + 2) + ')').classList.add('side1');
  1438. levelContainDom.querySelector('li:nth-child(' + (plast + 1) + ')').classList.add('side2');
  1439. levelContainDom.querySelector('li:nth-child(' + (plast + 4) + ')').classList.add('side1');
  1440. levelContainDom.querySelector('li:nth-child(' + (plast + 5) + ')').classList.add('side2');
  1441. }
  1442. else if (this.options.itemShowCount === 9) {
  1443. pdom = levelContainDom.querySelector('li:nth-child(' + (plast + 4) + ')');
  1444. pdom.classList.add('at');
  1445. levelContainDom.querySelector('li:nth-child(' + (plast + 3) + ')').classList.add('side1');
  1446. levelContainDom.querySelector('li:nth-child(' + (plast + 2) + ')').classList.add('side2');
  1447. levelContainDom.querySelector('li:nth-child(' + (plast + 5) + ')').classList.add('side1');
  1448. levelContainDom.querySelector('li:nth-child(' + (plast + 6) + ')').classList.add('side2');
  1449. }
  1450. return pdom;
  1451. },
  1452. setBase: function () {
  1453. if (this.options.cssUnit === 'rem') {
  1454. var dltDom = document.documentElement;
  1455. var dltStyle = window.getComputedStyle(dltDom, null);
  1456. var dltFontSize = dltStyle.fontSize;
  1457. try {
  1458. this.baseSize = /\d+(?:\.\d+)?/.exec(dltFontSize)[0];
  1459. }
  1460. catch(e) {
  1461. this.baseSize = 1;
  1462. }
  1463. }
  1464. else {
  1465. this.baseSize = 1;
  1466. }
  1467. },
  1468. toggleClassList: function (dom) {
  1469. Array.prototype.slice.call(dom.querySelectorAll('li')).forEach(function (v) {
  1470. if (v.classList.contains('at')) {
  1471. v.classList.remove('at');
  1472. }
  1473. else if (v.classList.contains('side1')) {
  1474. v.classList.remove('side1');
  1475. }
  1476. else if (v.classList.contains('side2')) {
  1477. v.classList.remove('side2');
  1478. }
  1479. })
  1480. }
  1481. }
  1482. if (typeof module != 'undefined' && module.exports) {
  1483. module.exports = IosSelect;
  1484. }
  1485. else if (typeof define == 'function' && define.amd) {
  1486. define(function () {
  1487. return IosSelect;
  1488. });
  1489. }
  1490. else {
  1491. window.IosSelect = IosSelect;
  1492. }
  1493. })();