【问题标题】:Prevent background events trigger when clicking on overlay div单击覆盖div时防止触发背景事件
【发布时间】:2016-05-23 20:32:47
【问题描述】:

我有一个Backbone 视图,并在其中附加了一些事件:

var View1 = Backbone.View.extend({

  initialize: function() {
      // ...
  },

   events: {
      "touchend .elem": "callback",
       // ...
    }

  render: function() {
      // ...
  }

});

现在,当我渲染View1 时,首先渲染另一个视图(View2),它有一个覆盖View1 元素的divdiv 有这些 CSS 属性:

.overlay {
    background-color: rgba(0, 0, 0, 0.22) !important;
    z-index: 500;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    position: fixed;
}

View2 几秒钟后消失。 问题是,如果我在覆盖消失之前单击它,则会触发覆盖下的事件,因此在我的示例中,将调用 callback 函数。

我试图通过这样做将虚假事件附加到View2

var View2 = Backbone.View.extend({

  initialize: function() {
      // ...
  },

  events: {
      // ...
      "touchend .overlay":   "overlayCallback"
  },

  overlayCallback: function( event ) {
      if ( event ) {
          event.preventDefault();
          event.stopImmediatePropagation();
          event.stopPropagation();
      }
      return false;
  },

  render: function() {
      // ...
  }

});

但这并不能解决我的问题。

当用户点击View2覆盖div时,如何防止View1触发事件?

谢谢

【问题讨论】:

  • 我们不知道你的 DOM 的结构。您应该提供minimal reproducible example
  • @TJ,我认为没有必要,因为我只需要一种方法来禁用覆盖 div 下所有 div 的触摸事件。谢谢
  • 这完全取决于你所说的 under 是什么意思。它可能在眼睛下方,只是视觉上。我们需要知道这些元素在 DOM 中的关系,以及整个 CSS 中的关系。简而言之,minimal reproducible example
  • @Frank 你解决了吗?

标签: javascript backbone.js


【解决方案1】:

假设 View1 调用 View2,你可以这样做:

  1. 将 View1 作为参数添加到 View2s 的初始化方法
  2. 然后,使用undelegateEvents - 方法中所述 在 view2 的初始化方法中的主干js-docs 禁用 view1 的事件暂时。
  3. 在 View2 关闭时,重新委托 您的事件使用 delegateEvents - View1 中的方法或创建一个 view1 中的自定义方法,并从 view2 对 view1 的引用中调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2019-07-04
    • 2015-04-28
    相关资源
    最近更新 更多