简体   繁体   中英

Creating and firing touch events on a touch enabled browser?

I am trying to fire touch events in my javascript to simulate user interactions for the purpose of testing features. I have tried the following snippet:

try {
    var targetElement = document.elementFromPoint(55, 155);
    console.log(targetElement);
    var evt = document.createEvent('UIEvent');
    evt.initTouchEvent('touchstart', true, true);

    evt.view = window;
    evt.altKey = false;
    evt.ctrlKey = false;
    evt.shiftKey = false;
    evt.metaKey = false;

    targetElement.dispatchEvent(evt);
} catch (except){
    alert(except);
}

The above code throws the exception 'TypeError: Result of expression 'evt.initTouchEvent[undefined]' is not a function.'

Can somebody point out what I'm doing wrong?

According to w3c touch spec , TouchEvent is a subclass of UIEvent. Try creating it like:

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

change:

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

to:

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

worked for me with nightly chrome build

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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