Is it possible to add an eventlistener on a DIV?

感情迁移 提交于 2019-12-20 09:11:11

问题


I know this function:

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

But is it possible to add this to a div? Example:

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

I haven't tested it yet, maybe some of you know if it works?


回答1:


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



回答2:


The other way round if you are not using addEventListener, probably a alternative to get control over ID.

 $(document).ready(function () {
            $('#container1').on("contextmenu", function (e) {
                e.preventDefault();
            });
        });



回答3:


Of course, let's assume you have to insert text in h1 element when a user clicks on the button. It's pretty easy to bind HTML's specific element to addEventListener() method

<button id="button">Show me</button>


<h1 id="name"></h1>


document.getElementById("button").addEventListener("click", function(){
  document.getElementById("name").innerHTML = "Hello World!";
});


来源:https://stackoverflow.com/questions/4164053/is-it-possible-to-add-an-eventlistener-on-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!