common2.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. (function(w){
  2. // 空函数
  3. function shield(){
  4. return false;
  5. }
  6. document.addEventListener('touchstart',shield,false);//取消浏览器的所有事件,使得active的样式在手机上正常生效
  7. document.oncontextmenu=shield;//屏蔽选择函数
  8. // H5 plus事件处理
  9. var ws=null,as='pop-in';
  10. function plusReady(){
  11. ws=plus.webview.currentWebview();
  12. // Android处理返回键
  13. plus.key.addEventListener('backbutton',function(){
  14. back();
  15. },false);
  16. compatibleAdjust();
  17. }
  18. if(w.plus){
  19. plusReady();
  20. }else{
  21. document.addEventListener('plusready',plusReady,false);
  22. }
  23. // DOMContentLoaded事件处理
  24. var domready=false;
  25. document.addEventListener('DOMContentLoaded',function(){
  26. domready=true;
  27. gInit();
  28. document.body.onselectstart=shield;
  29. compatibleAdjust();
  30. },false);
  31. // 处理返回事件
  32. w.back=function(hide){
  33. if(w.plus){
  34. ws||(ws=plus.webview.currentWebview());
  35. if(hide||ws.preate){
  36. ws.hide('auto');
  37. }else{
  38. ws.close('auto');
  39. }
  40. }else if(history.length>1){
  41. history.back();
  42. }else{
  43. w.close();
  44. }
  45. };
  46. // 处理点击事件
  47. var openw=null,waiting=null;
  48. /**
  49. * 打开新窗口
  50. * @param {URIString} id : 要打开页面url
  51. * @param {boolean} wa : 是否显示等待框
  52. * @param {boolean} ns : 是否不自动显示
  53. * @param {JSON} ws : Webview窗口属性
  54. */
  55. w.clicked=function(id,wa,ns,ws){
  56. if(openw){//避免多次打开同一个页面
  57. return null;
  58. }
  59. if(w.plus){
  60. wa&&(waiting=plus.nativeUI.showWaiting());
  61. ws=ws||{};
  62. ws.scrollIndicator||(ws.scrollIndicator='none');
  63. ws.scalable||(ws.scalable=false);
  64. var pre='';//'http://192.168.1.178:8080/h5/';
  65. openw=plus.webview.create(pre+id,id,ws);
  66. ns||openw.addEventListener('loaded',function(){//页面加载完成后才显示
  67. // setTimeout(function(){//延后显示可避免低端机上动画时白屏
  68. openw.show(as);
  69. closeWaiting();
  70. // },200);
  71. },false);
  72. openw.addEventListener('close',function(){//页面关闭后可再次打开
  73. openw=null;
  74. },false);
  75. return openw;
  76. }else{
  77. w.open(id);
  78. }
  79. return null;
  80. };
  81. w.openDoc=function(t,c){
  82. var d=plus.webview.getWebviewById('document');
  83. if(d){
  84. d.evalJS('updateDoc("'+t+'","'+c+'")');
  85. }else{
  86. d=plus.webview.create('/plus/doc.html','document',{zindex:9999,popGesture:'hide'},{preate:true});
  87. d.addEventListener('loaded',function(){
  88. d.evalJS('updateDoc("'+t+'","'+c+'")');
  89. },false);
  90. }
  91. }
  92. /**
  93. * 关闭等待框
  94. */
  95. w.closeWaiting=function(){
  96. waiting&&waiting.close();
  97. waiting=null;
  98. }
  99. // 兼容性样式调整
  100. var adjust=false;
  101. function compatibleAdjust(){
  102. if(adjust||!w.plus||!domready){
  103. return;
  104. } // iOS平台使用滚动的div
  105. if('iOS'==plus.os.name){
  106. var t=document.getElementById("dcontent");
  107. t&&(t.className="sdcontent");
  108. t=document.getElementById("content");
  109. t&&(t.className="scontent");
  110. //iOS8横竖屏切换div不更新滚动问题
  111. var lasto=window.orientation;
  112. window.addEventListener("orientationchange",function(){
  113. var nowo=window.orientation;
  114. if(lasto!=nowo&&(90==nowo||-90==nowo)){
  115. window.dcontent&&(0==dcontent.scrollTop)&&(dcontent.scrollTop=1);
  116. window.content&&(0==content.scrollTop)&&(content.scrollTop=1);
  117. }
  118. lasto=nowo;
  119. },false);
  120. }
  121. adjust=true;
  122. };
  123. w.compatibleConfirm=function(){
  124. plus.nativeUI.confirm('本OS原生层面不提供该控件,需使用mui框架实现类似效果。请点击“确定”下载Hello mui示例',function(e){
  125. if(0==e.index){
  126. plus.runtime.openURL("http://www.dcloud.io/hellomui/");
  127. }
  128. },"",["确定","取消"]);
  129. }
  130. // 通用元素对象
  131. var _dout_=null,_dcontent_=null;
  132. w.gInit=function(){
  133. _dout_=document.getElementById("output");
  134. _dcontent_=document.getElementById("dcontent");
  135. };
  136. // 清空输出内容
  137. w.outClean=function(){
  138. _dout_.innerText="";
  139. _dout_.scrollTop=0;//在iOS8存在不滚动的现象
  140. };
  141. // 输出内容
  142. w.outSet=function(s){
  143. _dout_.innerText=s+"\n";
  144. (0==_dout_.scrollTop)&&(_dout_.scrollTop=1);//在iOS8存在不滚动的现象
  145. };
  146. // 输出行内容
  147. w.outLine=function(s){
  148. _dout_.innerText+=s+"\n";
  149. (0==_dout_.scrollTop)&&(_dout_.scrollTop=1);//在iOS8存在不滚动的现象
  150. };
  151. // 格式化时长字符串,格式为"HH:MM:SS"
  152. w.timeToStr=function(ts){
  153. if(isNaN(ts)){
  154. return "--:--:--";
  155. }
  156. var h=parseInt(ts/3600);
  157. var m=parseInt((ts%3600)/60);
  158. var s=parseInt(ts%60);
  159. return (ultZeroize(h)+":"+ultZeroize(m)+":"+ultZeroize(s));
  160. };
  161. // 格式化日期时间字符串,格式为"YYYY-MM-DD HH:MM:SS"
  162. w.dateToStr=function(d){
  163. return (d.getFullYear()+"-"+ultZeroize(d.getMonth()+1)+"-"+ultZeroize(d.getDate())+" "+ultZeroize(d.getHours())+":"+ultZeroize(d.getMinutes())+":"+ultZeroize(d.getSeconds()));
  164. };
  165. /**
  166. * zeroize value with length(default is 2).
  167. * @param {Object} v
  168. * @param {Number} l
  169. * @return {String}
  170. */
  171. w.ultZeroize=function(v,l){
  172. var z="";
  173. l=l||2;
  174. v=String(v);
  175. for(var i=0;i<l-v.length;i++){
  176. z+="0";
  177. }
  178. return z+v;
  179. };
  180. })(window);
  181. ;(function () {
  182. 'use strict';
  183. /**
  184. * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
  185. *
  186. * @codingstandard ftlabs-jsv2
  187. * @copyright The Financial Times Limited [All Rights Reserved]
  188. * @license MIT License (see LICENSE.txt)
  189. */
  190. /*jslint browser:true, node:true*/
  191. /*global define, Event, Node*/
  192. /**
  193. * Instantiate fast-clicking listeners on the specified layer.
  194. *
  195. * @constructor
  196. * @param {Element} layer The layer to listen on
  197. * @param {Object} [options={}] The options to override the defaults
  198. */
  199. function FastClick(layer, options) {
  200. var oldOnClick;
  201. options = options || {};
  202. /**
  203. * Whether a click is currently being tracked.
  204. *
  205. * @type boolean
  206. */
  207. this.trackingClick = false;
  208. /**
  209. * Timestamp for when click tracking started.
  210. *
  211. * @type number
  212. */
  213. this.trackingClickStart = 0;
  214. /**
  215. * The element being tracked for a click.
  216. *
  217. * @type EventTarget
  218. */
  219. this.targetElement = null;
  220. /**
  221. * X-coordinate of touch start event.
  222. *
  223. * @type number
  224. */
  225. this.touchStartX = 0;
  226. /**
  227. * Y-coordinate of touch start event.
  228. *
  229. * @type number
  230. */
  231. this.touchStartY = 0;
  232. /**
  233. * ID of the last touch, retrieved from Touch.identifier.
  234. *
  235. * @type number
  236. */
  237. this.lastTouchIdentifier = 0;
  238. /**
  239. * Touchmove boundary, beyond which a click will be cancelled.
  240. *
  241. * @type number
  242. */
  243. this.touchBoundary = options.touchBoundary || 10;
  244. /**
  245. * The FastClick layer.
  246. *
  247. * @type Element
  248. */
  249. this.layer = layer;
  250. /**
  251. * The minimum time between tap(touchstart and touchend) events
  252. *
  253. * @type number
  254. */
  255. this.tapDelay = options.tapDelay || 200;
  256. /**
  257. * The maximum time for a tap
  258. *
  259. * @type number
  260. */
  261. this.tapTimeout = options.tapTimeout || 700;
  262. if (FastClick.notNeeded(layer)) {
  263. return;
  264. }
  265. // Some old versions of Android don't have Function.prototype.bind
  266. function bind(method, context) {
  267. return function() { return method.apply(context, arguments); };
  268. }
  269. var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
  270. var context = this;
  271. for (var i = 0, l = methods.length; i < l; i++) {
  272. context[methods[i]] = bind(context[methods[i]], context);
  273. }
  274. // Set up event handlers as required
  275. if (deviceIsAndroid) {
  276. layer.addEventListener('mouseover', this.onMouse, true);
  277. layer.addEventListener('mousedown', this.onMouse, true);
  278. layer.addEventListener('mouseup', this.onMouse, true);
  279. }
  280. layer.addEventListener('click', this.onClick, true);
  281. layer.addEventListener('touchstart', this.onTouchStart, false);
  282. layer.addEventListener('touchmove', this.onTouchMove, false);
  283. layer.addEventListener('touchend', this.onTouchEnd, false);
  284. layer.addEventListener('touchcancel', this.onTouchCancel, false);
  285. // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
  286. // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
  287. // layer when they are cancelled.
  288. if (!Event.prototype.stopImmediatePropagation) {
  289. layer.removeEventListener = function(type, callback, capture) {
  290. var rmv = Node.prototype.removeEventListener;
  291. if (type === 'click') {
  292. rmv.call(layer, type, callback.hijacked || callback, capture);
  293. } else {
  294. rmv.call(layer, type, callback, capture);
  295. }
  296. };
  297. layer.addEventListener = function(type, callback, capture) {
  298. var adv = Node.prototype.addEventListener;
  299. if (type === 'click') {
  300. adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
  301. if (!event.propagationStopped) {
  302. callback(event);
  303. }
  304. }), capture);
  305. } else {
  306. adv.call(layer, type, callback, capture);
  307. }
  308. };
  309. }
  310. // If a handler is already declared in the element's onclick attribute, it will be fired before
  311. // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
  312. // adding it as listener.
  313. if (typeof layer.onclick === 'function') {
  314. // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
  315. // - the old one won't work if passed to addEventListener directly.
  316. oldOnClick = layer.onclick;
  317. layer.addEventListener('click', function(event) {
  318. oldOnClick(event);
  319. }, false);
  320. layer.onclick = null;
  321. }
  322. }
  323. /**
  324. * Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
  325. *
  326. * @type boolean
  327. */
  328. var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;
  329. /**
  330. * Android requires exceptions.
  331. *
  332. * @type boolean
  333. */
  334. var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;
  335. /**
  336. * iOS requires exceptions.
  337. *
  338. * @type boolean
  339. */
  340. var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;
  341. /**
  342. * iOS 4 requires an exception for select elements.
  343. *
  344. * @type boolean
  345. */
  346. var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
  347. /**
  348. * iOS 6.0-7.* requires the target element to be manually derived
  349. *
  350. * @type boolean
  351. */
  352. var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);
  353. /**
  354. * BlackBerry requires exceptions.
  355. *
  356. * @type boolean
  357. */
  358. var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;
  359. /**
  360. * Determine whether a given element requires a native click.
  361. *
  362. * @param {EventTarget|Element} target Target DOM element
  363. * @returns {boolean} Returns true if the element needs a native click
  364. */
  365. FastClick.prototype.needsClick = function(target) {
  366. switch (target.nodeName.toLowerCase()) {
  367. // Don't send a synthetic click to disabled inputs (issue #62)
  368. case 'button':
  369. case 'select':
  370. case 'textarea':
  371. if (target.disabled) {
  372. return true;
  373. }
  374. break;
  375. case 'input':
  376. // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
  377. if ((deviceIsIOS && target.type === 'file') || target.disabled) {
  378. return true;
  379. }
  380. break;
  381. case 'label':
  382. case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
  383. case 'video':
  384. return true;
  385. }
  386. return (/\bneedsclick\b/).test(target.className);
  387. };
  388. /**
  389. * Determine whether a given element requires a call to focus to simulate click into element.
  390. *
  391. * @param {EventTarget|Element} target Target DOM element
  392. * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
  393. */
  394. FastClick.prototype.needsFocus = function(target) {
  395. switch (target.nodeName.toLowerCase()) {
  396. case 'textarea':
  397. return true;
  398. case 'select':
  399. return !deviceIsAndroid;
  400. case 'input':
  401. switch (target.type) {
  402. case 'button':
  403. case 'checkbox':
  404. case 'file':
  405. case 'image':
  406. case 'radio':
  407. case 'submit':
  408. return false;
  409. }
  410. // No point in attempting to focus disabled inputs
  411. return !target.disabled && !target.readOnly;
  412. default:
  413. return (/\bneedsfocus\b/).test(target.className);
  414. }
  415. };
  416. /**
  417. * Send a click event to the specified element.
  418. *
  419. * @param {EventTarget|Element} targetElement
  420. * @param {Event} event
  421. */
  422. FastClick.prototype.sendClick = function(targetElement, event) {
  423. var clickEvent, touch;
  424. // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
  425. if (document.activeElement && document.activeElement !== targetElement) {
  426. document.activeElement.blur();
  427. }
  428. touch = event.changedTouches[0];
  429. // Synthesise a click event, with an extra attribute so it can be tracked
  430. clickEvent = document.createEvent('MouseEvents');
  431. clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
  432. clickEvent.forwardedTouchEvent = true;
  433. targetElement.dispatchEvent(clickEvent);
  434. };
  435. FastClick.prototype.determineEventType = function(targetElement) {
  436. //Issue #159: Android Chrome Select Box does not open with a synthetic click event
  437. if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
  438. return 'mousedown';
  439. }
  440. return 'click';
  441. };
  442. /**
  443. * @param {EventTarget|Element} targetElement
  444. */
  445. FastClick.prototype.focus = function(targetElement) {
  446. var length;
  447. // Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
  448. if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {
  449. length = targetElement.value.length;
  450. targetElement.setSelectionRange(length, length);
  451. } else {
  452. targetElement.focus();
  453. }
  454. };
  455. /**
  456. * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
  457. *
  458. * @param {EventTarget|Element} targetElement
  459. */
  460. FastClick.prototype.updateScrollParent = function(targetElement) {
  461. var scrollParent, parentElement;
  462. scrollParent = targetElement.fastClickScrollParent;
  463. // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
  464. // target element was moved to another parent.
  465. if (!scrollParent || !scrollParent.contains(targetElement)) {
  466. parentElement = targetElement;
  467. do {
  468. if (parentElement.scrollHeight > parentElement.offsetHeight) {
  469. scrollParent = parentElement;
  470. targetElement.fastClickScrollParent = parentElement;
  471. break;
  472. }
  473. parentElement = parentElement.parentElement;
  474. } while (parentElement);
  475. }
  476. // Always update the scroll top tracker if possible.
  477. if (scrollParent) {
  478. scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
  479. }
  480. };
  481. /**
  482. * @param {EventTarget} targetElement
  483. * @returns {Element|EventTarget}
  484. */
  485. FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
  486. // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
  487. if (eventTarget.nodeType === Node.TEXT_NODE) {
  488. return eventTarget.parentNode;
  489. }
  490. return eventTarget;
  491. };
  492. /**
  493. * On touch start, record the position and scroll offset.
  494. *
  495. * @param {Event} event
  496. * @returns {boolean}
  497. */
  498. FastClick.prototype.onTouchStart = function(event) {
  499. var targetElement, touch, selection;
  500. // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
  501. if (event.targetTouches.length > 1) {
  502. return true;
  503. }
  504. targetElement = this.getTargetElementFromEventTarget(event.target);
  505. touch = event.targetTouches[0];
  506. if (deviceIsIOS) {
  507. // Only trusted events will deselect text on iOS (issue #49)
  508. selection = window.getSelection();
  509. if (selection.rangeCount && !selection.isCollapsed) {
  510. return true;
  511. }
  512. if (!deviceIsIOS4) {
  513. // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
  514. // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
  515. // with the same identifier as the touch event that previously triggered the click that triggered the alert.
  516. // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
  517. // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
  518. // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
  519. // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
  520. // random integers, it's safe to to continue if the identifier is 0 here.
  521. if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
  522. event.preventDefault();
  523. return false;
  524. }
  525. this.lastTouchIdentifier = touch.identifier;
  526. // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
  527. // 1) the user does a fling scroll on the scrollable layer
  528. // 2) the user stops the fling scroll with another tap
  529. // then the event.target of the last 'touchend' event will be the element that was under the user's finger
  530. // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
  531. // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
  532. this.updateScrollParent(targetElement);
  533. }
  534. }
  535. this.trackingClick = true;
  536. this.trackingClickStart = event.timeStamp;
  537. this.targetElement = targetElement;
  538. this.touchStartX = touch.pageX;
  539. this.touchStartY = touch.pageY;
  540. // Prevent phantom clicks on fast double-tap (issue #36)
  541. if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
  542. event.preventDefault();
  543. }
  544. return true;
  545. };
  546. /**
  547. * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
  548. *
  549. * @param {Event} event
  550. * @returns {boolean}
  551. */
  552. FastClick.prototype.touchHasMoved = function(event) {
  553. var touch = event.changedTouches[0], boundary = this.touchBoundary;
  554. if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
  555. return true;
  556. }
  557. return false;
  558. };
  559. /**
  560. * Update the last position.
  561. *
  562. * @param {Event} event
  563. * @returns {boolean}
  564. */
  565. FastClick.prototype.onTouchMove = function(event) {
  566. if (!this.trackingClick) {
  567. return true;
  568. }
  569. // If the touch has moved, cancel the click tracking
  570. if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
  571. this.trackingClick = false;
  572. this.targetElement = null;
  573. }
  574. return true;
  575. };
  576. /**
  577. * Attempt to find the labelled control for the given label element.
  578. *
  579. * @param {EventTarget|HTMLLabelElement} labelElement
  580. * @returns {Element|null}
  581. */
  582. FastClick.prototype.findControl = function(labelElement) {
  583. // Fast path for newer browsers supporting the HTML5 control attribute
  584. if (labelElement.control !== undefined) {
  585. return labelElement.control;
  586. }
  587. // All browsers under test that support touch events also support the HTML5 htmlFor attribute
  588. if (labelElement.htmlFor) {
  589. return document.getElementById(labelElement.htmlFor);
  590. }
  591. // If no for attribute exists, attempt to retrieve the first labellable descendant element
  592. // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
  593. return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
  594. };
  595. /**
  596. * On touch end, determine whether to send a click event at once.
  597. *
  598. * @param {Event} event
  599. * @returns {boolean}
  600. */
  601. FastClick.prototype.onTouchEnd = function(event) {
  602. var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
  603. if (!this.trackingClick) {
  604. return true;
  605. }
  606. // Prevent phantom clicks on fast double-tap (issue #36)
  607. if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
  608. this.cancelNextClick = true;
  609. return true;
  610. }
  611. if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
  612. return true;
  613. }
  614. // Reset to prevent wrong click cancel on input (issue #156).
  615. this.cancelNextClick = false;
  616. this.lastClickTime = event.timeStamp;
  617. trackingClickStart = this.trackingClickStart;
  618. this.trackingClick = false;
  619. this.trackingClickStart = 0;
  620. // On some iOS devices, the targetElement supplied with the event is invalid if the layer
  621. // is performing a transition or scroll, and has to be re-detected manually. Note that
  622. // for this to function correctly, it must be called *after* the event target is checked!
  623. // See issue #57; also filed as rdar://13048589 .
  624. if (deviceIsIOSWithBadTarget) {
  625. touch = event.changedTouches[0];
  626. // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
  627. targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
  628. targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
  629. }
  630. targetTagName = targetElement.tagName.toLowerCase();
  631. if (targetTagName === 'label') {
  632. forElement = this.findControl(targetElement);
  633. if (forElement) {
  634. this.focus(targetElement);
  635. if (deviceIsAndroid) {
  636. return false;
  637. }
  638. targetElement = forElement;
  639. }
  640. } else if (this.needsFocus(targetElement)) {
  641. // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
  642. // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
  643. if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
  644. this.targetElement = null;
  645. return false;
  646. }
  647. this.focus(targetElement);
  648. this.sendClick(targetElement, event);
  649. // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
  650. // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
  651. if (!deviceIsIOS || targetTagName !== 'select') {
  652. this.targetElement = null;
  653. event.preventDefault();
  654. }
  655. return false;
  656. }
  657. if (deviceIsIOS && !deviceIsIOS4) {
  658. // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
  659. // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
  660. scrollParent = targetElement.fastClickScrollParent;
  661. if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
  662. return true;
  663. }
  664. }
  665. // Prevent the actual click from going though - unless the target node is marked as requiring
  666. // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
  667. if (!this.needsClick(targetElement)) {
  668. event.preventDefault();
  669. this.sendClick(targetElement, event);
  670. }
  671. return false;
  672. };
  673. /**
  674. * On touch cancel, stop tracking the click.
  675. *
  676. * @returns {void}
  677. */
  678. FastClick.prototype.onTouchCancel = function() {
  679. this.trackingClick = false;
  680. this.targetElement = null;
  681. };
  682. /**
  683. * Determine mouse events which should be permitted.
  684. *
  685. * @param {Event} event
  686. * @returns {boolean}
  687. */
  688. FastClick.prototype.onMouse = function(event) {
  689. // If a target element was never set (because a touch event was never fired) allow the event
  690. if (!this.targetElement) {
  691. return true;
  692. }
  693. if (event.forwardedTouchEvent) {
  694. return true;
  695. }
  696. // Programmatically generated events targeting a specific element should be permitted
  697. if (!event.cancelable) {
  698. return true;
  699. }
  700. // Derive and check the target element to see whether the mouse event needs to be permitted;
  701. // unless explicitly enabled, prevent non-touch click events from triggering actions,
  702. // to prevent ghost/doubleclicks.
  703. if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
  704. // Prevent any user-added listeners declared on FastClick element from being fired.
  705. if (event.stopImmediatePropagation) {
  706. event.stopImmediatePropagation();
  707. } else {
  708. // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
  709. event.propagationStopped = true;
  710. }
  711. // Cancel the event
  712. event.stopPropagation();
  713. event.preventDefault();
  714. return false;
  715. }
  716. // If the mouse event is permitted, return true for the action to go through.
  717. return true;
  718. };
  719. /**
  720. * On actual clicks, determine whether this is a touch-generated click, a click action occurring
  721. * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
  722. * an actual click which should be permitted.
  723. *
  724. * @param {Event} event
  725. * @returns {boolean}
  726. */
  727. FastClick.prototype.onClick = function(event) {
  728. var permitted;
  729. // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
  730. if (this.trackingClick) {
  731. this.targetElement = null;
  732. this.trackingClick = false;
  733. return true;
  734. }
  735. // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
  736. if (event.target.type === 'submit' && event.detail === 0) {
  737. return true;
  738. }
  739. permitted = this.onMouse(event);
  740. // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
  741. if (!permitted) {
  742. this.targetElement = null;
  743. }
  744. // If clicks are permitted, return true for the action to go through.
  745. return permitted;
  746. };
  747. /**
  748. * Remove all FastClick's event listeners.
  749. *
  750. * @returns {void}
  751. */
  752. FastClick.prototype.destroy = function() {
  753. var layer = this.layer;
  754. if (deviceIsAndroid) {
  755. layer.removeEventListener('mouseover', this.onMouse, true);
  756. layer.removeEventListener('mousedown', this.onMouse, true);
  757. layer.removeEventListener('mouseup', this.onMouse, true);
  758. }
  759. layer.removeEventListener('click', this.onClick, true);
  760. layer.removeEventListener('touchstart', this.onTouchStart, false);
  761. layer.removeEventListener('touchmove', this.onTouchMove, false);
  762. layer.removeEventListener('touchend', this.onTouchEnd, false);
  763. layer.removeEventListener('touchcancel', this.onTouchCancel, false);
  764. };
  765. /**
  766. * Check whether FastClick is needed.
  767. *
  768. * @param {Element} layer The layer to listen on
  769. */
  770. FastClick.notNeeded = function(layer) {
  771. var metaViewport;
  772. var chromeVersion;
  773. var blackberryVersion;
  774. var firefoxVersion;
  775. // Devices that don't support touch don't need FastClick
  776. if (typeof window.ontouchstart === 'undefined') {
  777. return true;
  778. }
  779. // Chrome version - zero for other browsers
  780. chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
  781. if (chromeVersion) {
  782. if (deviceIsAndroid) {
  783. metaViewport = document.querySelector('meta[name=viewport]');
  784. if (metaViewport) {
  785. // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
  786. if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
  787. return true;
  788. }
  789. // Chrome 32 and above with width=device-width or less don't need FastClick
  790. if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
  791. return true;
  792. }
  793. }
  794. // Chrome desktop doesn't need FastClick (issue #15)
  795. } else {
  796. return true;
  797. }
  798. }
  799. if (deviceIsBlackBerry10) {
  800. blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);
  801. // BlackBerry 10.3+ does not require Fastclick library.
  802. // https://github.com/ftlabs/fastclick/issues/251
  803. if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
  804. metaViewport = document.querySelector('meta[name=viewport]');
  805. if (metaViewport) {
  806. // user-scalable=no eliminates click delay.
  807. if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
  808. return true;
  809. }
  810. // width=device-width (or less than device-width) eliminates click delay.
  811. if (document.documentElement.scrollWidth <= window.outerWidth) {
  812. return true;
  813. }
  814. }
  815. }
  816. }
  817. // IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
  818. if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
  819. return true;
  820. }
  821. // Firefox version - zero for other browsers
  822. firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
  823. if (firefoxVersion >= 27) {
  824. // Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896
  825. metaViewport = document.querySelector('meta[name=viewport]');
  826. if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
  827. return true;
  828. }
  829. }
  830. // IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
  831. // http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
  832. if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
  833. return true;
  834. }
  835. return false;
  836. };
  837. /**
  838. * Factory method for creating a FastClick object
  839. *
  840. * @param {Element} layer The layer to listen on
  841. * @param {Object} [options={}] The options to override the defaults
  842. */
  843. FastClick.attach = function(layer, options) {
  844. return new FastClick(layer, options);
  845. };
  846. if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
  847. // AMD. Register as an anonymous module.
  848. define(function() {
  849. return FastClick;
  850. });
  851. } else if (typeof module !== 'undefined' && module.exports) {
  852. module.exports = FastClick.attach;
  853. module.exports.FastClick = FastClick;
  854. } else {
  855. window.FastClick = FastClick;
  856. }
  857. document.addEventListener('DOMContentLoaded', function() {
  858. FastClick.attach(document.body);
  859. }, false);
  860. }());