How do I programmatically create a TouchEvent in Chrome 41?

前端 未结 4 507
一整个雨季
一整个雨季 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:52

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

    /* 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 Touch and TouchEvent

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

    see Touch and TouchEvent constructors

提交回复
热议问题