【问题标题】:Toggling document touchmove on/off by adding / removing EventListener通过添加/删除 EventListener 来打开/关闭文档 touchmove
【发布时间】:2019-04-12 14:20:00
【问题描述】:

我有一个要求为移动设备上的身体滚动实现锁定/解锁功能,如下所示:

var myObj = {
 disableBodyScroll: function() {
    document.querySelector('body').addEventListener("touchmove", function(e) {
      e.preventDefault();
      return false;
    }, 
    {passive: false}
    ); 
  },
  enableBodyScroll: function() {
    document.querySelector('body').removeEventListener("touchmove", function(e) {
      e.preventDefault();
      return false;
    }, 
    {passive: false}
    ); 
  }
}

当我做myObj.disableBodyScroll() 时,它工作正常。 但是myObj.enableBodyScroll() 没有,我的滚动条保持锁定状态...

这有什么可能的原因吗?

参考:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

【问题讨论】:

  • stackoverflow 删除了我在问题开头的“你好”...

标签: javascript touch addeventlistener dom-events


【解决方案1】:

我认为这是因为您没有传递相同的侦听器函数。您的启用和禁用函数都会创建一个新的 eventListener 函数。所以removeEventListener找不到eventListener引用

试试这个:

var myObj = {
        handleTouchMove: function (e) {
            e.preventDefault();
            return false;
        },
        disableBodyScroll: function() {
            document.querySelector('body').addEventListener("touchmove", myObj.handleTouchMove, {passive: false}
            );
        },
        enableBodyScroll: function() {
            document.querySelector('body').removeEventListener("touchmove", myObj.handleTouchMove, {passive: false}
            );
        }
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多