简体   繁体   中英

How to use mobile touch events with pure javascript?

What is the syntax for mobile touch events in javascript? I tried:

window.document.body.ontouchstart = function() { alert(); }

and

window.document.body.touchstart = function() { alert(); }

It doesn't give any error. And nothing happens on touching the webpage. It seems like addEventListener is the way to go. But why doesn't window.document.body.ontouchstart directly work?

var theElement = document.getElementById("theElement");

theElement.addEventListener("touchstart", handlerFunction, false);

function handlerFunction(event) {
alert();
}

Try this code:

function foo(event) {
  alert();
}

var el = document.getElementsByTagName("canvas")[0];
  el.addEventListener("touchstart", foo(), false);

//or 

window.document.body.addEventListener("touchstart", foo(), false);

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