emulateTouch.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var trigger = require('./trigger');
  2. var root = require('./root');
  3. var hasTouchSupport = 'ontouchstart' in root;
  4. exports = function() {
  5. var el =
  6. arguments.length > 0 && arguments[0] !== undefined
  7. ? arguments[0]
  8. : document;
  9. if (hasTouchSupport) return;
  10. if (el._isEmulated) return;
  11. el._isEmulated = true;
  12. el.addEventListener('mousedown', onMouse('touchstart'), true);
  13. el.addEventListener('mousemove', onMouse('touchmove'), true);
  14. el.addEventListener('mouseup', onMouse('touchend'), true);
  15. };
  16. function onMouse(type) {
  17. return function(e) {
  18. if (e.which !== 1) return;
  19. trigger(e.target, type, {
  20. altKey: e.altKey,
  21. ctrlKey: e.ctrlKey,
  22. metaKey: e.metaKey,
  23. shiftKey: e.shiftKey,
  24. touches: getActiveTouches(e),
  25. targetTouches: getActiveTouches(e),
  26. changedTouches: createTouchList(e)
  27. });
  28. };
  29. }
  30. function getActiveTouches(e) {
  31. if (e.type == 'mouseup') return createTouchList();
  32. return createTouchList(e);
  33. }
  34. function Touch(target, identifier, pos, deltaX, deltaY) {
  35. deltaX = deltaX || 0;
  36. deltaY = deltaY || 0;
  37. this.identifier = identifier;
  38. this.target = target;
  39. this.clientX = pos.clientX + deltaX;
  40. this.clientY = pos.clientY + deltaY;
  41. this.screenX = pos.screenX + deltaX;
  42. this.screenY = pos.screenY + deltaY;
  43. this.pageX = pos.pageX + deltaX;
  44. this.pageY = pos.pageY + deltaY;
  45. }
  46. function createTouchList(e) {
  47. var touchList = [];
  48. touchList.item = function(index) {
  49. return this[index] || null;
  50. };
  51. if (e) {
  52. touchList.push(new Touch(e.target, 1, e, 0, 0));
  53. }
  54. return touchList;
  55. }
  56. module.exports = exports;