Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - Is it possible to add an eventlistener on a DIV?

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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...