touch.js 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. // http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/
  2. function touchHandler(event) {'use strict';
  3. var simulatedEvent,
  4. touches = event.changedTouches,
  5. first = touches[0],
  6. type = "";
  7. switch (event.type) {
  8. case "touchstart": type = "mousedown"; break;
  9. case "touchmove": type = "mousemove"; break;
  10. case "touchend": type = "mouseup"; break;
  11. default: return;
  12. }
  13. // initMouseEvent(type, canBubble, cancelable, view, clickCount,
  14. // screenX, screenY, clientX, clientY, ctrlKey,
  15. // altKey, shiftKey, metaKey, button, relatedTarget);
  16. simulatedEvent = document.createEvent("MouseEvent");
  17. simulatedEvent.initMouseEvent(type, true, true, window, 1,
  18. first.screenX, first.screenY,
  19. first.clientX, first.clientY, false,
  20. false, false, false, 0/*left*/, null);
  21. if (touches.length < 2) {
  22. first.target.dispatchEvent(simulatedEvent);
  23. event.preventDefault();
  24. }
  25. }
  26. document.addEventListener('touchstart', touchHandler, true);
  27. document.addEventListener('touchmove', touchHandler, true);
  28. document.addEventListener('touchend', touchHandler, true);
  29. document.addEventListener('touchcancel', touchHandler, true);