How do I programmatically create a TouchEvent in Chrome 41?

前端 未结 4 516
一整个雨季
一整个雨季 2020-12-16 18:21

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:

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 18:57

    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 TouchEvent is a subclass of UIEvent.

    Update

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

    So perhaps a try/catch would be in order:

    try {
    
      document.createEvent('TouchEvent');
    
    } catch (e) {
    
      console.log('No touching!');
    
    }
    

提交回复
热议问题