可以在一个DIV元素上添加事件监听器吗?

48

我知道这个函数:

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

但是能否将它添加到一个

元素中呢?例如:

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

我还没有测试过它,也许你们中的一些人知道它是否有效?


是的。可以的。http://www.alistapart.com/articles/domtricks2/ - Dennis G
3个回答

56

是的,那就是你要做的。

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

或者使用jQuery

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

JQuery的bind方法还可以接受第三个布尔类型参数来处理事件冒泡。默认值在JavaScript代码中等同于false,因此为了保持一致性,建议在两个列表中都加上或都不加上该参数。 - schilippe

0
当然,假设您必须在用户单击按钮时插入文本到

元素中。将HTML的特定元素绑定到addEventListener()方法非常容易。
<button id="button">Show me</button>


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


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


0
如果您没有使用addEventListener,那么另一种方法可能是通过替代方案来控制ID。
 $(document).ready(function () {
            $('#container1').on("contextmenu", function (e) {
                e.preventDefault();
            });
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接