如何使用纯javascript移动触摸事件?

时间:2016-05-16 11:29:22

标签: javascript html css

javascript中移动触摸事件的语法是什么?我试过了:

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

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

它不会给出任何错误。触摸网页时没有任何反应。似乎addEventListener是要走的路。但为什么window.document.body.ontouchstart没有直接起作用?

2 个答案:

答案 0 :(得分:2)

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

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

function handlerFunction(event) {
alert();
}

答案 1 :(得分:1)

试试这段代码:

function foo(event) {
  alert();
}

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

//or 

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