我搜索了过去 30 分钟,但没有找到解决方案。
我想在元素上触发 touchstart
事件。
这会触发 touchstart
事件:
var e = document.createEvent('MouseEvent');
e.initMouseEvent("touchstart", true, true, window, 1, screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget);
target.dispatchEvent(e);
请注意,变量是由我的函数定义的
但这有一个问题。 event
对象没有 touches
属性。所以这样的事情是行不通的:
var touch = e.touches[0];
有没有办法手动触发 touchstart
事件(它应该适用于 Android >= 4.0 和启用触摸功能的 Chrome [DevTools])?
请注意,我不想使用任何像 jQuery 这样的框架。使用 jQuery,可以轻松地在元素上创建 touchevent
;)
最佳答案
根据W3C
var e = document.createEvent('TouchEvent');
然后,也改变
e.initMouseEvent();
到
e.initTouchEvent();
当您创建了 touchstart
事件时。
W3C 链接显示:
Some user agents implement an initTouchEvent method as part of the TouchEvent interface. When this method is available, scripts can use it to initialize the properties of a TouchEvent object, including its TouchList properties (which can be initialized with values returned from createTouchList). The initTouchEvent method is not yet standardized, but it may appear in some form in a future specification.
所以你可能不得不求助于 e.initUIEvent('touchstart', true, true);
此外,官方规范还指出 TouchList
对象是可选,可以使用 createTouchList
方法手动创建。要将触摸添加到该列表,您必须调用createTouch
方法,您将在其中传递所有坐标等:
6.1 Methods #createTouch Creates a Touch object with the specified attributes. Parameter | Type | Nullable | Optional | Description view | WindowProxy | ✘ | ✘ | target | EventTarget | ✘ | ✘ | identifier| long | ✘ | ✘ | pageX | long | ✘ | ✘ | pageY | long | ✘ | ✘ | screenX | long | ✘ | ✘ | screenY | long | ✘ | ✘ | Return type: Touch #createTouchList Creates a TouchList object consisting of zero or more Touch objects. Calling this method with no arguments creates a TouchList with no objects in it and length 0 (zero). Parameter | Type | Nullable | Optional | Description touches | Touch | ✘ | ✔ | Return type: TouchList
If that doesn't work, you could try this:
var e = document.createEvent('UIEvent');
e.initUIEvent();
应该可以,无论如何它比 createEvent('MouseEvent')
更有意义......
但出于测试目的,为什么不打开 Chrome 控制台并选中模拟触摸事件
,并将用户代理覆盖到 Android 4。(Ctrl+Shift+j > 单击右下角的齿轮,然后选择覆盖,在那里你会找到你需要的所有设置)
由于触摸事件在标准化方面还有很长的路要走,所以事实证明 touches
属性不是 RO(还吗?) ,因此您可以使用此快速修复(OP 找到并使用了所需的结果):
var e = document.createEvent('TouchEvent');
e.touches = [{pageX: pageX, pageY: pageY}];
我认为(如果不是这样的话我简直不敢相信)比:
e.touches = e.createTouchList(
e.createTouch(window, target, 0, pageX, pageY, screenX, screenY)
);
关于javascript - 手动触发触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18059860/