Is it possible to add an eventlistener on a DIV?

后端 未结 3 429
Happy的楠姐
Happy的楠姐 2021-01-31 15:56

I know this function:

document.addEventListener(\'touchstart\', function(event) {
    alert(event.touches.length);
}, false);

But is it possibl

3条回答
  •  失恋的感觉
    2021-01-31 16:07

    Yeah, that's how you do it.

    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!");
      }
    }
    

    Or with jQuery

    $(function(){
      $("#div").bind("touchstart", function (event) {
        alert(event.touches.length);
      });
    });
    

提交回复
热议问题