mouse-simulator.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. ;(function() {
  2. /**
  3. * 模拟PC端 mouse 事件
  4. */
  5. function touchEventToMouseEvent(event, eventType) {
  6. var te = event.targetTouches[0] || event.changedTouches[0];
  7. var clientX = te.clientX, clientY = te.clientY, screenX = te.screenX, screenY = te.screenY;
  8. var simEvent = new MouseEvent(eventType, {
  9. clientX: clientX,
  10. clientY: clientY,
  11. screenX: screenX,
  12. screenY: screenY,
  13. button: 0,
  14. buttons: 0,
  15. bubbles: true
  16. });
  17. return simEvent;
  18. }
  19. /**
  20. * only trigger touches when the left mousebutton has been pressed
  21. * @param touchType
  22. * @returns {Function}
  23. */
  24. function onMouse(touchType) {
  25. return function(ev) {
  26. if(touchType == "mousemove") {
  27. // ev.preventDefault()
  28. }
  29. var simEvent = touchEventToMouseEvent(ev, touchType);
  30. if (simEvent != null) {
  31. ev.target.dispatchEvent(simEvent);
  32. }
  33. };
  34. }
  35. /**
  36. * MouseEmulator initializer
  37. */
  38. function MouseEmulator() {
  39. window.addEventListener('touchstart', onMouse('mousedown'), true);
  40. window.addEventListener('touchmove', onMouse('mousemove'), true);
  41. window.addEventListener('touchend', onMouse('mouseup'), true);
  42. }
  43. MouseEmulator();
  44. })();