javascript 手动触发触摸事件

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

manually trigger touch event

javascripteventstouch

提问by AndreM96

I searched for the past 30 minutes, but didn't find a solution.

我搜索了过去 30 分钟,但没有找到解决方案。

I want to trigger a touchstartevent on an element.

我想touchstart在一个元素上触发一个事件。

This fires the touchstartevent:

这将触发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);

Note that the variables are defined by my function

请注意,变量是由我的函数定义的

But there's a problem with that. The eventobject doesn't have a touchesproperty. So something like this won't work:

但是这有一个问题。该event对象没有touches属性。所以这样的事情是行不通的:

var touch = e.touches[0];

Is there a way to trigger a touchstartevent manually (it should work on Android >= 4.0 and Chrome with touch enabled [DevTools]) ?

有没有办法touchstart手动触发事件(它应该适用于 Android >= 4.0 和启用触摸功能的 Chrome [DevTools])?

Please note, that I do NOT want to use any framework like jQuery. With jQuery it's easy to create a toucheventon an element ;)

请注意,我不想使用任何框架,如 jQuery。使用 jQuery 很容易touchevent在元素上创建;)

采纳答案by Elias Van Ootegem

According to W3C

根据W3C

var e = document.createEvent('TouchEvent');

Then, also change

然后,也改变

e.initMouseEvent();

to

e.initTouchEvent();

As you've created a touchstartevent.

因为您已经创建了一个touchstart事件。

The W3C link says:

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.

一些用户代理实现了 initTouchEvent 方法作为 TouchEvent 接口的一部分。当此方法可用时,脚本可以使用它来初始化 TouchEvent 对象的属性,包括其 TouchList 属性(可以使用从 createTouchList 返回的值进行初始化)。initTouchEvent 方法尚未标准化,但它可能会以某种形式出现在未来的规范中。

So you'll might have to resort to e.initUIEvent('touchstart', true, true);
In addition, the official spec also states that the TouchListobject is optional, and can be created manually using the createTouchListmethod. To add a touchto that list, you'll have to call the createTouchmethod, where you'll pass all coordinates and such:

所以你可能不得不求助于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();

should work, it makes more sense than createEvent('MouseEvent')at any rate...
But for testing purposes, why not open your chrome console and check Emulate touch events, plus override user agent to Android 4. (Ctrl+Shift+j > click the gear bottom right corner, and select Overrides, there you'll find all the settings you need)

应该可以工作,它比createEvent('MouseEvent')无论如何都更有意义......
但出于测试目的,为什么不打开你的 chrome 控制台并检查Emulate touch events,并将用户代理覆盖到 Android 4。(Ctrl+Shift+j > 单击右下角的齿轮,并选择覆盖,在那里你会找到你需要的所有设置)

Since the touch-events have a long way to go, still in terms of their becoming standardized, it turns out the touchesproperty is notRO (yet?), so you can use this quick-fix (which the OP found and used with the desired result):

由于触摸事件还有很长的路要走,仍然在标准化方面,事实证明该touches属性不是RO(还没有?),因此您可以使用此快速修复(OP 发现并与想要的结果):

var e = document.createEvent('TouchEvent');
e.touches = [{pageX: pageX, pageY: pageY}];

Which, I think (I can't believe it if it weren't the case) is faster than:

其中,我认为(如果不是这样,我简直不敢相信)比以下更快:

e.touches = e.createTouchList(
    e.createTouch(window, target, 0, pageX, pageY, screenX, screenY)
);

回答by Derek Henderson

I know this has been answered, but I too struggled to find an answer to this problem and the accepted answer didn't work for me. In the end, the solution I found is really very simple and has support across browsers:

我知道这已经得到了回答,但我也很难找到这个问题的答案,而且公认的答案对我不起作用。最后,我找到的解决方案非常简单,并且支持跨浏览器:

var e = new Event('touchstart');
target.dispatchEvent(e);

That's it. Couldn't be easier.

而已。再简单不过了。

回答by Theva

I have come up with this solution (javascript native), works for me

我想出了这个解决方案(javascript native),对我有用

var el = document.getElementById('myDivId');
// desktop
el.click();

// mobile
if (window.matchMedia("(max-width: 768px)").matches) {
        // createEvent(), event.initEvent() are Depricated see Ref: [enter link description here][1]
        // var event = document.createEvent("Event"); 
        // event.initEvent("touchstart", false, true);
        // event.initEvent("touchend", false, true);
        // So the solution is:
        var event1 = new Event('touchstart');
        var event2 = new Event('touchend'); 
        el.dispatchEvent(event1); 
        el.dispatchEvent(event2);
  }

回答by Chase Choi

In 2019, we can use TouchEventand Touch.

在 2019 年,我们可以使用TouchEventTouch

Touchis an experimental technology

Touch是一种实验技术

For example,

例如,

const touch = new Touch({
  identifier: "123",
  target: target,
});

const touchEvent = new TouchEvent("touchstart", {
  touches: [touch],
  view: window,
  cancelable: true,
  bubbles: true,
});

target.dispatchEvent(touchEvent);

I created gist. try it simple.

我创建了要点。试试简单。

回答by Praveen

We can trigger like this:

我们可以这样触发:

$playBtn.bind((is_touch_device) ? 'touchstart' : 'click', playfunction);