iscroll-lite.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /*!
  2. * iScroll Lite base on iScroll v4.1.6 ~ Copyright (c) 2011 Matteo Spinelli, http://cubiq.org
  3. * Released under MIT license, http://cubiq.org/license
  4. */
  5. (function(){
  6. var m = Math,
  7. mround = function (r) { return r >> 0; },
  8. vendor = (/webkit/i).test(navigator.appVersion) ? 'webkit' :
  9. (/firefox/i).test(navigator.userAgent) ? 'Moz' :
  10. 'opera' in window ? 'O' : '',
  11. // Browser capabilities
  12. isAndroid = (/android/gi).test(navigator.appVersion),
  13. isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
  14. isPlaybook = (/playbook/gi).test(navigator.appVersion),
  15. isTouchPad = (/hp-tablet/gi).test(navigator.appVersion),
  16. has3d = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(),
  17. hasTouch = 'ontouchstart' in window && !isTouchPad,
  18. hasTransform = vendor + 'Transform' in document.documentElement.style,
  19. hasTransitionEnd = isIDevice || isPlaybook,
  20. nextFrame = (function() {
  21. return window.requestAnimationFrame
  22. || window.webkitRequestAnimationFrame
  23. || window.mozRequestAnimationFrame
  24. || window.oRequestAnimationFrame
  25. || window.msRequestAnimationFrame
  26. || function(callback) { return setTimeout(callback, 17); }
  27. })(),
  28. cancelFrame = (function () {
  29. return window.cancelRequestAnimationFrame
  30. || window.webkitCancelAnimationFrame
  31. || window.webkitCancelRequestAnimationFrame
  32. || window.mozCancelRequestAnimationFrame
  33. || window.oCancelRequestAnimationFrame
  34. || window.msCancelRequestAnimationFrame
  35. || clearTimeout
  36. })(),
  37. // Events
  38. RESIZE_EV = 'onorientationchange' in window ? 'orientationchange' : 'resize',
  39. START_EV = hasTouch ? 'touchstart' : 'mousedown',
  40. MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
  41. END_EV = hasTouch ? 'touchend' : 'mouseup',
  42. CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseup',
  43. // Helpers
  44. trnOpen = 'translate' + (has3d ? '3d(' : '('),
  45. trnClose = has3d ? ',0)' : ')',
  46. // Constructor
  47. iScroll = function (el, options) {
  48. var that = this,
  49. doc = document,
  50. i;
  51. that.wrapper = typeof el == 'object' ? el : doc.getElementById(el);
  52. that.wrapper.style.overflow = 'hidden';
  53. that.scroller = that.wrapper.children[0];
  54. // Default options
  55. that.options = {
  56. hScroll: true,
  57. vScroll: true,
  58. x: 0,
  59. y: 0,
  60. bounce: true,
  61. bounceLock: false,
  62. momentum: true,
  63. lockDirection: true,
  64. useTransform: true,
  65. useTransition: false,
  66. // Events
  67. onRefresh: null,
  68. onBeforeScrollStart: function (e) {
  69. //e.preventDefault();
  70. var target = e.target;
  71. while (target.nodeType != 1) target = target.parentNode;
  72. if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
  73. e.preventDefault();
  74. }
  75. },
  76. onScrollStart: null,
  77. onBeforeScrollMove: null,
  78. onScrollMove: null,
  79. onBeforeScrollEnd: null,
  80. onScrollEnd: null,
  81. onTouchEnd: null,
  82. onDestroy: null
  83. };
  84. // User defined options
  85. for (i in options) that.options[i] = options[i];
  86. // Set starting position
  87. that.x = that.options.x;
  88. that.y = that.options.y;
  89. // Normalize options
  90. that.options.useTransform = hasTransform ? that.options.useTransform : false;
  91. that.options.hScrollbar = that.options.hScroll && that.options.hScrollbar;
  92. that.options.vScrollbar = that.options.vScroll && that.options.vScrollbar;
  93. that.options.useTransition = hasTransitionEnd && that.options.useTransition;
  94. // Set some default styles
  95. that.scroller.style[vendor + 'TransitionProperty'] = that.options.useTransform ? '-' + vendor.toLowerCase() + '-transform' : 'top left';
  96. that.scroller.style[vendor + 'TransitionDuration'] = '0';
  97. that.scroller.style[vendor + 'TransformOrigin'] = '0 0';
  98. if (that.options.useTransition) that.scroller.style[vendor + 'TransitionTimingFunction'] = 'cubic-bezier(0.33,0.66,0.66,1)';
  99. if (that.options.useTransform) that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose;
  100. else that.scroller.style.cssText += ';position:absolute;top:' + that.y + 'px;left:' + that.x + 'px';
  101. that.refresh();
  102. that._bind(RESIZE_EV, window);
  103. that._bind(START_EV);
  104. if (!hasTouch) that._bind('mouseout', that.wrapper);
  105. };
  106. // Prototype
  107. iScroll.prototype = {
  108. enabled: true,
  109. x: 0,
  110. y: 0,
  111. steps: [],
  112. scale: 1,
  113. handleEvent: function (e) {
  114. var that = this;
  115. switch(e.type) {
  116. case START_EV:
  117. if (!hasTouch && e.button !== 0) return;
  118. that._start(e);
  119. break;
  120. case MOVE_EV: that._move(e); break;
  121. case END_EV:
  122. case CANCEL_EV: that._end(e); break;
  123. case RESIZE_EV: that._resize(); break;
  124. case 'mouseout': that._mouseout(e); break;
  125. case 'webkitTransitionEnd': that._transitionEnd(e); break;
  126. }
  127. },
  128. _resize: function () {
  129. this.refresh();
  130. },
  131. _pos: function (x, y) {
  132. x = this.hScroll ? x : 0;
  133. y = this.vScroll ? y : 0;
  134. if (this.options.useTransform) {
  135. this.scroller.style[vendor + 'Transform'] = trnOpen + x + 'px,' + y + 'px' + trnClose + ' scale(' + this.scale + ')';
  136. } else {
  137. x = mround(x);
  138. y = mround(y);
  139. this.scroller.style.left = x + 'px';
  140. this.scroller.style.top = y + 'px';
  141. }
  142. this.x = x;
  143. this.y = y;
  144. },
  145. _start: function (e) {
  146. var that = this,
  147. point = hasTouch ? e.touches[0] : e,
  148. matrix, x, y;
  149. if (!that.enabled) return;
  150. if (that.options.onBeforeScrollStart) that.options.onBeforeScrollStart.call(that, e);
  151. if (that.options.useTransition) that._transitionTime(0);
  152. that.moved = false;
  153. that.animating = false;
  154. that.zoomed = false;
  155. that.distX = 0;
  156. that.distY = 0;
  157. that.absDistX = 0;
  158. that.absDistY = 0;
  159. that.dirX = 0;
  160. that.dirY = 0;
  161. if (that.options.momentum) {
  162. if (that.options.useTransform) {
  163. // Very lame general purpose alternative to CSSMatrix
  164. matrix = getComputedStyle(that.scroller, null)[vendor + 'Transform'].replace(/[^0-9-.,]/g, '').split(',');
  165. x = matrix[4] * 1;
  166. y = matrix[5] * 1;
  167. } else {
  168. x = getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '') * 1;
  169. y = getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '') * 1;
  170. }
  171. if (x != that.x || y != that.y) {
  172. if (that.options.useTransition) that._unbind('webkitTransitionEnd');
  173. else cancelFrame(that.aniTime);
  174. that.steps = [];
  175. that._pos(x, y);
  176. }
  177. }
  178. that.startX = that.x;
  179. that.startY = that.y;
  180. that.pointX = point.pageX;
  181. that.pointY = point.pageY;
  182. that.startTime = e.timeStamp || Date.now();
  183. if (that.options.onScrollStart) that.options.onScrollStart.call(that, e);
  184. that._bind(MOVE_EV);
  185. that._bind(END_EV);
  186. that._bind(CANCEL_EV);
  187. },
  188. _move: function (e) {
  189. var that = this,
  190. point = hasTouch ? e.touches[0] : e,
  191. deltaX = point.pageX - that.pointX,
  192. deltaY = point.pageY - that.pointY,
  193. newX = that.x + deltaX,
  194. newY = that.y + deltaY,
  195. timestamp = e.timeStamp || Date.now();
  196. if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
  197. that.pointX = point.pageX;
  198. that.pointY = point.pageY;
  199. // Slow down if outside of the boundaries
  200. if (newX > 0 || newX < that.maxScrollX) {
  201. newX = that.options.bounce ? that.x + (deltaX / 2) : newX >= 0 || that.maxScrollX >= 0 ? 0 : that.maxScrollX;
  202. }
  203. if (newY > 0 || newY < that.maxScrollY) {
  204. newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= 0 || that.maxScrollY >= 0 ? 0 : that.maxScrollY;
  205. }
  206. if (that.absDistX < 6 && that.absDistY < 6) {
  207. that.distX += deltaX;
  208. that.distY += deltaY;
  209. that.absDistX = m.abs(that.distX);
  210. that.absDistY = m.abs(that.distY);
  211. return;
  212. }
  213. // Lock direction
  214. if (that.options.lockDirection) {
  215. if (that.absDistX > that.absDistY + 5) {
  216. newY = that.y;
  217. deltaY = 0;
  218. } else if (that.absDistY > that.absDistX + 5) {
  219. newX = that.x;
  220. deltaX = 0;
  221. }
  222. }
  223. that.moved = true;
  224. that._pos(newX, newY);
  225. that.dirX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
  226. that.dirY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
  227. if (timestamp - that.startTime > 300) {
  228. that.startTime = timestamp;
  229. that.startX = that.x;
  230. that.startY = that.y;
  231. }
  232. if (that.options.onScrollMove) that.options.onScrollMove.call(that, e);
  233. },
  234. _end: function (e) {
  235. if (hasTouch && e.touches.length != 0) return;
  236. var that = this,
  237. point = hasTouch ? e.changedTouches[0] : e,
  238. target, ev,
  239. momentumX = { dist:0, time:0 },
  240. momentumY = { dist:0, time:0 },
  241. duration = (e.timeStamp || Date.now()) - that.startTime,
  242. newPosX = that.x,
  243. newPosY = that.y,
  244. newDuration;
  245. that._unbind(MOVE_EV);
  246. that._unbind(END_EV);
  247. that._unbind(CANCEL_EV);
  248. if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);
  249. if (!that.moved) {
  250. if (hasTouch) {
  251. // Find the last touched element
  252. target = point.target;
  253. while (target.nodeType != 1) target = target.parentNode;
  254. if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
  255. ev = document.createEvent('MouseEvents');
  256. ev.initMouseEvent('click', true, true, e.view, 1,
  257. point.screenX, point.screenY, point.clientX, point.clientY,
  258. e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
  259. 0, null);
  260. ev._fake = true;
  261. target.dispatchEvent(ev);
  262. }
  263. }
  264. that._resetPos(200);
  265. if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
  266. return;
  267. }
  268. if (duration < 300 && that.options.momentum) {
  269. momentumX = newPosX ? that._momentum(newPosX - that.startX, duration, -that.x, that.scrollerW - that.wrapperW + that.x, that.options.bounce ? that.wrapperW : 0) : momentumX;
  270. momentumY = newPosY ? that._momentum(newPosY - that.startY, duration, -that.y, (that.maxScrollY < 0 ? that.scrollerH - that.wrapperH + that.y : 0), that.options.bounce ? that.wrapperH : 0) : momentumY;
  271. newPosX = that.x + momentumX.dist;
  272. newPosY = that.y + momentumY.dist;
  273. if ((that.x > 0 && newPosX > 0) || (that.x < that.maxScrollX && newPosX < that.maxScrollX)) momentumX = { dist:0, time:0 };
  274. if ((that.y > 0 && newPosY > 0) || (that.y < that.maxScrollY && newPosY < that.maxScrollY)) momentumY = { dist:0, time:0 };
  275. }
  276. if (momentumX.dist || momentumY.dist) {
  277. newDuration = m.max(m.max(momentumX.time, momentumY.time), 10);
  278. that.scrollTo(mround(newPosX), mround(newPosY), newDuration);
  279. if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
  280. return;
  281. }
  282. that._resetPos(200);
  283. if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
  284. },
  285. _resetPos: function (time) {
  286. var that = this,
  287. resetX = that.x >= 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x,
  288. resetY = that.y >= 0 || that.maxScrollY > 0 ? 0 : that.y < that.maxScrollY ? that.maxScrollY : that.y;
  289. if (resetX == that.x && resetY == that.y) {
  290. if (that.moved) {
  291. if (that.options.onScrollEnd) that.options.onScrollEnd.call(that); // Execute custom code on scroll end
  292. that.moved = false;
  293. }
  294. return;
  295. }
  296. that.scrollTo(resetX, resetY, time || 0);
  297. },
  298. _mouseout: function (e) {
  299. var t = e.relatedTarget;
  300. if (!t) {
  301. this._end(e);
  302. return;
  303. }
  304. while (t = t.parentNode) if (t == this.wrapper) return;
  305. this._end(e);
  306. },
  307. _transitionEnd: function (e) {
  308. var that = this;
  309. if (e.target != that.scroller) return;
  310. that._unbind('webkitTransitionEnd');
  311. that._startAni();
  312. },
  313. /**
  314. *
  315. * Utilities
  316. *
  317. */
  318. _startAni: function () {
  319. var that = this,
  320. startX = that.x, startY = that.y,
  321. startTime = Date.now(),
  322. step, easeOut,
  323. animate;
  324. if (that.animating) return;
  325. if (!that.steps.length) {
  326. that._resetPos(400);
  327. return;
  328. }
  329. step = that.steps.shift();
  330. if (step.x == startX && step.y == startY) step.time = 0;
  331. that.animating = true;
  332. that.moved = true;
  333. if (that.options.useTransition) {
  334. that._transitionTime(step.time);
  335. that._pos(step.x, step.y);
  336. that.animating = false;
  337. if (step.time) that._bind('webkitTransitionEnd');
  338. else that._resetPos(0);
  339. return;
  340. }
  341. animate = function () {
  342. var now = Date.now(),
  343. newX, newY;
  344. if (now >= startTime + step.time) {
  345. that._pos(step.x, step.y);
  346. that.animating = false;
  347. if (that.options.onAnimationEnd) that.options.onAnimationEnd.call(that); // Execute custom code on animation end
  348. that._startAni();
  349. return;
  350. }
  351. now = (now - startTime) / step.time - 1;
  352. easeOut = m.sqrt(1 - now * now);
  353. newX = (step.x - startX) * easeOut + startX;
  354. newY = (step.y - startY) * easeOut + startY;
  355. that._pos(newX, newY);
  356. if (that.animating) that.aniTime = nextFrame(animate);
  357. };
  358. animate();
  359. },
  360. _transitionTime: function (time) {
  361. this.scroller.style[vendor + 'TransitionDuration'] = time + 'ms';
  362. },
  363. _momentum: function (dist, time, maxDistUpper, maxDistLower, size) {
  364. var deceleration = 0.0006,
  365. speed = m.abs(dist) / time,
  366. newDist = (speed * speed) / (2 * deceleration),
  367. newTime = 0, outsideDist = 0;
  368. // Proportinally reduce speed if we are outside of the boundaries
  369. if (dist > 0 && newDist > maxDistUpper) {
  370. outsideDist = size / (6 / (newDist / speed * deceleration));
  371. maxDistUpper = maxDistUpper + outsideDist;
  372. speed = speed * maxDistUpper / newDist;
  373. newDist = maxDistUpper;
  374. } else if (dist < 0 && newDist > maxDistLower) {
  375. outsideDist = size / (6 / (newDist / speed * deceleration));
  376. maxDistLower = maxDistLower + outsideDist;
  377. speed = speed * maxDistLower / newDist;
  378. newDist = maxDistLower;
  379. }
  380. newDist = newDist * (dist < 0 ? -1 : 1);
  381. newTime = speed / deceleration;
  382. return { dist: newDist, time: mround(newTime) };
  383. },
  384. _offset: function (el) {
  385. var left = -el.offsetLeft,
  386. top = -el.offsetTop;
  387. while (el = el.offsetParent) {
  388. left -= el.offsetLeft;
  389. top -= el.offsetTop;
  390. }
  391. return { left: left, top: top };
  392. },
  393. _bind: function (type, el, bubble) {
  394. (el || this.scroller).addEventListener(type, this, !!bubble);
  395. },
  396. _unbind: function (type, el, bubble) {
  397. (el || this.scroller).removeEventListener(type, this, !!bubble);
  398. },
  399. /**
  400. *
  401. * Public methods
  402. *
  403. */
  404. destroy: function () {
  405. var that = this;
  406. that.scroller.style[vendor + 'Transform'] = '';
  407. // Remove the event listeners
  408. that._unbind(RESIZE_EV, window);
  409. that._unbind(START_EV);
  410. that._unbind(MOVE_EV);
  411. that._unbind(END_EV);
  412. that._unbind(CANCEL_EV);
  413. that._unbind('mouseout', that.wrapper);
  414. if (that.options.useTransition) that._unbind('webkitTransitionEnd');
  415. if (that.options.onDestroy) that.options.onDestroy.call(that);
  416. },
  417. refresh: function () {
  418. var that = this,
  419. offset;
  420. that.wrapperW = that.wrapper.clientWidth;
  421. that.wrapperH = that.wrapper.clientHeight;
  422. that.scrollerW = that.scroller.offsetWidth;
  423. that.scrollerH = that.scroller.offsetHeight;
  424. that.maxScrollX = that.wrapperW - that.scrollerW;
  425. that.maxScrollY = that.wrapperH - that.scrollerH;
  426. that.dirX = 0;
  427. that.dirY = 0;
  428. that.hScroll = that.options.hScroll && that.maxScrollX < 0;
  429. that.vScroll = that.options.vScroll && (!that.options.bounceLock && !that.hScroll || that.scrollerH > that.wrapperH);
  430. offset = that._offset(that.wrapper);
  431. that.wrapperOffsetLeft = -offset.left;
  432. that.wrapperOffsetTop = -offset.top;
  433. that.scroller.style[vendor + 'TransitionDuration'] = '0';
  434. that._resetPos(200);
  435. },
  436. scrollTo: function (x, y, time, relative) {
  437. var that = this,
  438. step = x,
  439. i, l;
  440. that.stop();
  441. if (!step.length) step = [{ x: x, y: y, time: time, relative: relative }];
  442. for (i=0, l=step.length; i<l; i++) {
  443. if (step[i].relative) { step[i].x = that.x - step[i].x; step[i].y = that.y - step[i].y; }
  444. that.steps.push({ x: step[i].x, y: step[i].y, time: step[i].time || 0 });
  445. }
  446. that._startAni();
  447. },
  448. scrollToElement: function (el, time) {
  449. var that = this, pos;
  450. el = el.nodeType ? el : that.scroller.querySelector(el);
  451. if (!el) return;
  452. pos = that._offset(el);
  453. pos.left += that.wrapperOffsetLeft;
  454. pos.top += that.wrapperOffsetTop;
  455. pos.left = pos.left > 0 ? 0 : pos.left < that.maxScrollX ? that.maxScrollX : pos.left;
  456. pos.top = pos.top > 0 ? 0 : pos.top < that.maxScrollY ? that.maxScrollY : pos.top;
  457. time = time === undefined ? m.max(m.abs(pos.left)*2, m.abs(pos.top)*2) : time;
  458. that.scrollTo(pos.left, pos.top, time);
  459. },
  460. disable: function () {
  461. this.stop();
  462. this._resetPos(0);
  463. this.enabled = false;
  464. // If disabled after touchstart we make sure that there are no left over events
  465. this._unbind(MOVE_EV);
  466. this._unbind(END_EV);
  467. this._unbind(CANCEL_EV);
  468. },
  469. enable: function () {
  470. this.enabled = true;
  471. },
  472. stop: function () {
  473. cancelFrame(this.aniTime);
  474. this.steps = [];
  475. this.moved = false;
  476. this.animating = false;
  477. }
  478. };
  479. if (typeof exports !== 'undefined') exports.iScroll = iScroll;
  480. else window.iScroll = iScroll;
  481. })();