javascript 在启用触摸的浏览器上创建和触发触摸事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5713393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating and firing touch events on a touch enabled browser?
提问by prk
I am trying to fire touch events in my javascript to simulate user interactions for the purpose of testing features. I have tried the following snippet:
我试图在我的 javascript 中触发触摸事件来模拟用户交互以测试功能。我尝试了以下代码段:
try {
var targetElement = document.elementFromPoint(55, 155);
console.log(targetElement);
var evt = document.createEvent('UIEvent');
evt.initTouchEvent('touchstart', true, true);
evt.view = window;
evt.altKey = false;
evt.ctrlKey = false;
evt.shiftKey = false;
evt.metaKey = false;
targetElement.dispatchEvent(evt);
} catch (except){
alert(except);
}
The above code throws the exception 'TypeError: Result of expression 'evt.initTouchEvent[undefined]' is not a function.'
上面的代码抛出异常'TypeError: Result of expression 'evt.initTouchEvent[undefined]' is not a function。'
Can somebody point out what I'm doing wrong?
有人可以指出我做错了什么吗?
采纳答案by vbence
According to w3c touch spec, TouchEventis a subclass of UIEvent. Try creating it like:
根据w3c touch spec,TouchEvent是 UIEvent 的子类。尝试像这样创建它:
var evt = document.createEvent('TouchEvent');
回答by Vladimir
change:
改变:
evt.initTouchEvent('touchstart', true, true);
to:
到:
evt.initUIEvent('touchstart', true, true);
worked for me with nightly chrome build
使用夜间 chrome 构建对我来说有效

