如果iframe中发生了鼠标按下,文档不会触发mousemove事件

document won't fire mousemove event if mousedown occurred in iframe

本文关键字:事件 mousemove 文档 iframe 发生了 鼠标 如果      更新时间:2023-09-26

我有一个相同的原始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);
});

我的问题是,如果鼠标下降发生在iframe和鼠标离开iframe,文档不会触发它自己的鼠标移动事件,直到鼠标上升发生。

我已经尝试在鼠标离开iframe时触发iframe和文档中的mouseup,但是文档的mousemove事件将不会恢复,直到发生物理的mouseup。

这就是我在一个有多个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中没有。

使用对象文字表示法,您可以向.on()中添加多个事件。然后我添加了。contents()来让所有的事件在Iframe内工作。这是一个工作小提琴

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

当您从页面调用上述代码时,需要一些时间来加载框架主体。因此,它不能附加框架鼠标移动事件监听器。如果你用settimeout函数调用它,它将能够获取帧的内容,move将被附加到帧的主体。

:)