简体   繁体   English

手动触发触摸事件

[英]manually trigger touch event

I searched for the past 30 minutes, but didn't find a solution.我搜索了过去 30 分钟,但没有找到解决方案。

I want to trigger a touchstart event on an element.我想在一个元素上触发一个touchstart事件。

This fires the touchstart event:这将触发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 event object doesn't have a touches property. event对象没有touches属性。 So something like this won't work:所以这样的事情是行不通的:

var touch = e.touches[0];

Is there a way to trigger a touchstart event 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.请注意,我不想使用任何框架,如 jQuery。 With jQuery it's easy to create a touchevent on an element ;)使用 jQuery 很容易在元素上创建touchevent ;)

According to W3C根据W3C

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

Then, also change然后,也改变

e.initMouseEvent();

to

e.initTouchEvent();

As you've created a touchstart event.因为您已经创建了一个touchstart事件。

The W3C link says: W3C 链接说:

Some user agents implement an initTouchEvent method as part of the TouchEvent interface.一些用户代理实现了 initTouchEvent 方法作为 TouchEvent 接口的一部分。 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).当此方法可用时,脚本可以使用它来初始化 TouchEvent 对象的属性,包括其 TouchList 属性(可以使用从 createTouchList 返回的值进行初始化)。 The initTouchEvent method is not yet standardized, but it may appear in some form in a future specification. initTouchEvent 方法尚未标准化,但它可能会以某种形式出现在未来的规范中。

So you'll might have to resort to e.initUIEvent('touchstart', true, true);所以你可能不得不求助于e.initUIEvent('touchstart', true, true);
In addition, the official spec also states that the TouchList object is optional , and can be created manually using the createTouchList method.此外,官方规范还声明TouchList对象是可选的,可以使用createTouchList方法手动创建。 To add a touch to that list, you'll have to call the createTouch method, where you'll pass all coordinates and such:要向该列表添加触摸,您必须调用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...应该可以工作,无论如何它比createEvent('MouseEvent')更有意义......
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)但是出于测试目的,为什么不打开您的 chrome 控制台并检查Emulate touch events ,并将用户代理覆盖到 Android 4。(Ctrl+Shift+j > 单击右下角的齿轮,然后选择 Overrides,您会在那里找到所有您需要的设置)

Since the touch-events have a long way to go, still in terms of their becoming standardized, it turns out the touches property is not RO (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)
);

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.再简单不过了。

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);
  }

In 2019, we can use TouchEvent and Touch .在 2019 年,我们可以使用TouchEventTouch

Touch is 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 .我创建了gist try it simple.试试简单。

我们可以这样触发:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM