是否可以在DIV上添加eventlistener?

Ros*_*ist 31 javascript css events touch dom-events

我知道这个功能:

document.addEventListener('touchstart', function(event) {
    alert(event.touches.length);
}, false);
Run Code Online (Sandbox Code Playgroud)

但是有可能将它添加到div中吗?例:

document.getElementById("div").addEventListener('touchstart', function(event) {
        alert(event.touches.length);
    }, false);
Run Code Online (Sandbox Code Playgroud)

我还没测试过,也许有些人知道吗?

iRy*_*ell 43

是的,你就是这样做的.

document.getElementById("div").addEventListener("touchstart", touchHandler, false);
document.getElementById("div").addEventListener("touchmove", touchHandler, false);
document.getElementById("div").addEventListener("touchend", touchHandler, false);

function touchHandler(e) {
  if (e.type == "touchstart") {
    alert("You touched the screen!");
  } else if (e.type == "touchmove") {
    alert("You moved your finger!");
  } else if (e.type == "touchend" || e.type == "touchcancel") {
    alert("You removed your finger from the screen!");
  }
}
Run Code Online (Sandbox Code Playgroud)

或者使用jQuery

$(function(){
  $("#div").bind("touchstart", function (event) {
    alert(event.touches.length);
  });
});
Run Code Online (Sandbox Code Playgroud)