iscroll-lite.js 16 KB

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