Czy można dodać eventlistener do DIV?

Znam tę funkcję:

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

Ale czy można to dodać do div? Przykład:

document.getElementById("div").addEventListener('touchstart', function(event) {
        alert(event.touches.length);
    }, false);
Nie testowałem jeszcze, może ktoś z was wie?
Author: Tim S. Van Haren, 2010-11-12

2 answers

Tak to się robi.

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

Lub z jQuery

$(function(){
  $("#div").bind("touchstart", function (event) {
    alert(event.touches.length);
  });
});
 37
Author: arby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-11-12 11:30:39

Odwrotnie, jeśli nie używasz addEventListener, prawdopodobnie alternatywą dla uzyskania kontroli nad ID.

 $(document).ready(function () {
            $('#container1').on("contextmenu", function (e) {
                e.preventDefault();
            });
        });
 0
Author: KiranSolkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-22 12:32:35