我搜索了过去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);
Run Code Online (Sandbox Code Playgroud)
请注意,变量由我的函数定义
但这有一个问题.该event对象没有touches属性.所以像这样的东西不起作用:
var touch = e.touches[0];
Run Code Online (Sandbox Code Playgroud)
有没有办法touchstart手动触发事件(它应该在Android> = 4.0和Chrome启用触摸[DevTools])?
请注意,我不想使用像jQuery这样的任何框架.使用jQuery,可以轻松地touchevent在元素上创建;)
我正在尝试为单元测试创建触摸事件.阅读https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent后,我希望我能做到:
document.createEvent('TouchEvent');
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
未捕获的DOMException:无法在'Document'上执行'createEvent':提供的事件类型('TouchEvent')无效.
我看到在启用触摸的浏览器上创建和触发触摸事件?,这似乎也表明createEvent()是要走的路.
我也尝试通过构造函数创建事件,该函数适用于MouseEvent和WheelEvent:
new window.TouchEvent()
Run Code Online (Sandbox Code Playgroud)
但我也在这里得到一个错误:
未捕获的TypeError:非法构造函数
我尝试使用Firefox 36,但基于http://caniuse.com/#search=touch,我并不惊讶地看到:
NotSupportedError:不支持操作
跑完之后
document.createEvent('TouchEvent')
Run Code Online (Sandbox Code Playgroud)
Firefox中没有window.TouchEvent构造函数,这也不足为奇了.
我有什么想法我做错了吗?