🏠 Home 

触屏转鼠标事件

将触摸事件转换为鼠标事件

  1. // ==UserScript==
  2. // @name 触屏转鼠标事件
  3. // @version 1.0
  4. // @description 将触摸事件转换为鼠标事件
  5. // @author ChatGPT
  6. // @match *://*/*
  7. // @grant none
  8. // @run-at document-end
  9. // @namespace https://greasyfork.org/users/452911
  10. // ==/UserScript==
  11. (function() {
  12. 'use strict';
  13. // 创建鼠标事件
  14. function createMouseEvent(type, touchEvent) {
  15. return new MouseEvent(type, {
  16. bubbles: true, // 事件是否应该冒泡
  17. cancelable: true, // 事件是否可以被取消
  18. view: window, // 事件的视图
  19. clientX: touchEvent.clientX, // 触摸点的水平坐标
  20. clientY: touchEvent.clientY // 触摸点的垂直坐标
  21. });
  22. }
  23. // 触摸事件转换为鼠标事件
  24. function touchToMouse(e) {
  25. const touches = e.changedTouches;
  26. for (let i = 0; i < touches.length; i++) {
  27. const touch = touches[i];
  28. const mouseEvent = createMouseEvent(
  29. e.type === 'touchstart' ? 'mousedown' :
  30. e.type === 'touchend' ? 'mouseup' :
  31. 'mousemove', touch
  32. );
  33. touch.target.dispatchEvent(mouseEvent);
  34. }
  35. }
  36. // 监听触摸事件并转换为鼠标事件
  37. document.addEventListener('touchstart', touchToMouse, false);
  38. document.addEventListener('touchend', touchToMouse, false);
  39. document.addEventListener('touchmove', touchToMouse, false);
  40. })();