【问题标题】:How to remove touchevent in js?如何在js中删除touchevent?
【发布时间】:2012-12-02 13:11:19
【问题描述】:

我正在尝试在第一次触摸后删除 touchevent。
我已经尝试了下一个代码,但它不起作用:

ourCanvas.addEventListener("touchstart", function(){
    evt.preventDefault();
    startGame();
    ourGameCanvas.removeEventListener("touchstart");
}, false);`

【问题讨论】:

    标签: javascript dom-events touch-event


    【解决方案1】:

    您需要将原始函数的引用传递给removeEventListener

    ourCanvas.addEventListener("touchstart", function funcref(evt) {
        evt.preventDefault();
        startGame();
        ourCanvas.removeEventListener("touchstart", funcref, false);
    }, false);

    在前面的代码中,我将匿名函数表达式转换为命名函数表达式 (funcref),以便稍后在函数中使用它。

    我将ourGameCanvas 重命名为ourCanvas。仅当元素、事件名称、函数引用 useCapture 标志与addEventListener 使用的相同时,才能删除事件侦听器。

    【讨论】:

      【解决方案2】:

      removeEventListener 方法需要与addEventListener 方法相同的参数...换句话说:

      document.body.addEventListener('touchstart',function touchStartHandler(e)
      {//use named function
          document.body.removeEventListener('touchstart',touchStartHandler, flase);
      },false);
      

      attachEventdetachEvent 也是如此(如果您正在编码以支持 IE

      【讨论】:

      • 这个例子不起作用,因为touchStartHandler 是一个命名函数表达式,而不是一个函数声明。因此,命名函数在touchStartHandler 函数的范围之外不可用。 (旁注:IE8 不支持画布和触摸事件,所以不用担心attachEvent)。
      • @RobW 我知道 IE8 不支持画布和触摸事件,以防 OP 为非触摸设备或其他东西委派点击事件。在函数参考上,您当然是对的:我提供的 sn-p 令人困惑且不正确
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2015-12-03
      相关资源
      最近更新 更多