【问题标题】:document won't fire mousemove event if mousedown occurred in iframe如果 iframe 中发生 mousedown,则文档不会触发 mousemove 事件
【发布时间】:2013-05-25 18:25:57
【问题描述】:

我有一个相同的来源 iframe。 iframe 中的鼠标事件在文档中触发,如下所示:

// this won't work
$('iframe').contents().find('body').on('mousedown mouseup mousemove', function(e) {
  $(document).trigger(e);
});

// this does work
$('iframe').contents().on('mousedown mouseup mousemove', function(e) {
  $(document).trigger(e);
});

我的问题是,如果 mousedown 发生在 iframe 中并且鼠标离开 iframe,文档不会触发它自己的 mousemove 事件,直到 mouseup 发生。

我已经尝试在鼠标离开 iframe 后同时在 iframe 和文档中触发 mouseup,但文档 mousemove 事件在发生物理 mouseup 之前不会恢复。

【问题讨论】:

    标签: javascript jquery events iframe mousemove


    【解决方案1】:

    这对我来说适用于具有多个 iFrame 的页面:

    $(function() {
        $('iframe').each(function(index) {
            $(this).load(function () {
                $(this).contents().on("mousedown", function (e) {
                    $(document).trigger(e);
                })
                .on("mouseup", function (e) {
                    $(document).trigger(e);
                });
            });
    
        });
    });
    

    它也只适用于一个 iframe。重要的部分是在绑定事件之前等待帧加载完成,否则可能无法正常工作。在我的例子中,鼠标事件在一个 iframe 中被正确检测到,但在另一个 iframe 中没有。

    【讨论】:

      【解决方案2】:

      使用对象文字表示法,您可以将多个事件添加到 .on()。然后我添加了 .contents() 以使您的所有事件都在 iframe 中工作。 here's a working fiddle

      $('.myiframe').contents().on({
          mousedown: function () {
              console.log('mouse down triggered');
          },
          mouseup: function () {
              console.log('mouse up triggered');
          },
          mousemove: function() {
              console.log('mouse move triggered');
          }
      });
      

      【讨论】:

      • 是的,这解决了它,我一直将我的事件绑定到 iframe 内的主体,一旦鼠标离开 iframe 主体,它就会停止触发。
      【解决方案3】:

      当你从一个页面调用上面的代码时,加载框架体需要一些时间。因此它无法附加帧 mousemove 事件侦听器。如果您使用 settimeout 函数调用它,它将能够获取帧的内容,并且 movemove 将附加到帧的主体。

      :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-30
        • 1970-01-01
        • 2020-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-19
        相关资源
        最近更新 更多