javascript 如何在 Chrome 41 中以编程方式创建 TouchEvent?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29018151/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:58:12  来源:igfitidea点击:

How do I programmatically create a TouchEvent in Chrome 41?

javascriptgoogle-chrome

提问by exavatar

I am trying to create a touch event for a unit test. After reading https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent, I expected that I would be able to do:

我正在尝试为单元测试创​​建触摸事件。阅读https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent 后,我希望我能够做到:

document.createEvent('TouchEvent');

But I get this error:

但我收到此错误:

Uncaught DOMException: Failed to execute 'createEvent' on 'Document': The provided event type ('TouchEvent') is invalid.

未捕获的 DOMException:无法在“文档”上执行“createEvent”:提供的事件类型(“TouchEvent”)无效。

I saw Creating and firing touch events on a touch enabled browser?, which also seems to indicate that createEvent() is the way to go.

在启用触摸的浏览器上看到了创建和触发触摸事件?,这似乎也表明 createEvent() 是要走的路。

I also tried creating the event via constructor, which works for, say, MouseEvent and WheelEvent:

我还尝试通过构造函数创建事件,例如,它适用于 MouseEvent 和 WheelEvent:

new window.TouchEvent()

But I get an error here, too:

但我在这里也遇到错误:

Uncaught TypeError: Illegal constructor

未捕获的类型错误:非法构造函数

I tried in Firefox 36, but based on http://caniuse.com/#search=touch, I wasn't surprised to see:

我在 Firefox 36 中尝试过,但基于http://caniuse.com/#search=touch,我并不惊讶地看到:

NotSupportedError: Operation is not supported

NotSupportedError: 不支持操作

After running

运行后

document.createEvent('TouchEvent')

There is not event a window.TouchEvent constructor in Firefox, which is, again, not surprising.

Firefox 中没有 event a window.TouchEvent 构造函数,这也不足为奇。

Any ideas what I am doing wrong?

任何想法我做错了什么?

采纳答案by exavatar

It looks like

看起来像

document.createEvent('TouchEvent'); 

works if you are using an actual mobile device or mobile emulation.

如果您使用的是实际的移动设备或移动仿真,则可以使用。

回答by fhdhsni

I don't know if it works in other browsers but in chrome you can do something like

我不知道它是否适用于其他浏览器,但在 chrome 中你可以做类似的事情

/* eventType is 'touchstart', 'touchmove', 'touchend'... */
function sendTouchEvent(x, y, element, eventType) {
  const touchObj = new Touch({
    identifier: Date.now(),
    target: element,
    clientX: x,
    clientY: y,
    radiusX: 2.5,
    radiusY: 2.5,
    rotationAngle: 10,
    force: 0.5,
  });

  const touchEvent = new TouchEvent(eventType, {
    cancelable: true,
    bubbles: true,
    touches: [touchObj],
    targetTouches: [],
    changedTouches: [touchObj],
    shiftKey: true,
  });

  element.dispatchEvent(touchEvent);
}

const myElement = document.getElementById('foo')

sendTouchEvent(150, 150, myElement, 'touchstart');
sendTouchEvent(220, 200, myElement, 'touchmove');
sendTouchEvent(220, 200, myElement, 'touchend');

To test if a given browser supports Touchand TouchEvent

测试给定的浏览器是否支持TouchTouchEvent

if (typeof Touch !== 'undefined' &&
    typeof TouchEvent !== 'undefined' &&
    Touch.length === 1 &&
    TouchEvent.length === 1) {
       sendTouchEvent(200, 200, myElement, 'touchmove');
}

see Touch and TouchEvent constructors

请参阅Touch 和 TouchEvent 构造函数

回答by shennan

I'm guessing the only way to do it without throwing an exception is to be more explicit in the type of event you wish to create:

我猜想在不抛出异常的情况下做到这一点的唯一方法是在您希望创建的事件类型中更加明确:

var evt = document.createEvent('UIEvent');

evt.initUIEvent('touchstart', true, true);

The TouchEventis a subclass of UIEvent.

的TouchEvent是的子类的UIEvent

Update

更新

As mentioned above, while on an actual device (or emulating a device), one can easily create a TouchEvent using the standard document.createEventmethod.

如上所述,在实际设备(或模拟设备)上,可以使用标准document.createEvent方法轻松创建 TouchEvent 。

So perhaps a try/catch would be in order:

所以也许尝试/捕获是为了:

try {

  document.createEvent('TouchEvent');

} catch (e) {

  console.log('No touching!');

}

回答by Rob

Update: This will not actually result in an instance of TouchEvent. lame.

更新:这实际上不会导致 TouchEvent 的实例。瘸。

I did it like this:

我是这样做的:

var type = 'start'; // or move, end
var event = document.createEvent('Event');
event.initEvent('touch' + type, true, true);     
event.constructor.name; // Event (not TouchEvent)

You'll also need to set the touches on the event. That's another can of worms as some browsers support the document.createTouch and document.createTouchList methods and some don't. In browsers that don't you just create and array of JS objects that are "TouchEvent-like". This looks like:

您还需要设置事件的触摸。这是另一种蠕虫病毒,因为有些浏览器支持 document.createTouch 和 document.createTouchList 方法,有些则不支持。在浏览器中,您不只是创建和“类似 TouchEvent”的 JS 对象数组。这看起来像:

var point = {x: 10, y: 10 };
event.touches = [{
    target: someElement,
    identifier: Date.now() + i,
    pageX: point.x,
    pageY: point.y,
    screenX: point.x,
    screenY: point.y,
    clientX: point.x,
    clientY: point.y
}]