从iframe接收mousemove事件

问题描述 投票:9回答:6

我有一个javascript应用程序,它为文档添加了一个mousemove监听器。问题:当鼠标移动到iframe上时,不会调用该函数。

有没有办法将这些事件传递给根文档?

javascript mousemove event-passthrough
6个回答
4
投票

如果iframe中的文档位于同一document.domain中,则可以非常轻松地完成此操作。

如果你有相同的document.domain,你也必须在iframe中设置一个mousemove监听器,并将值传递给父页面。

如果文档不在同一个document.domain上,它会变得非常复杂,你需要iframes页面来运行设置mousemove事件监听器的javascript本身。然后你可以进行如下所述的跨框架通信:http://softwareas.com/cross-domain-communication-with-iframes

否则,由于浏览器强制执行的原始策略相同,您运气不佳。


35
投票

pointer-events: none;放在框架的样式中。

我自己遇到了这个问题,发现这个解决方案效果很好而且非常简单!


3
投票

我刚才遇到了同样的问题,我想出了这个问题:

$("iframe").contents().find("body").mousemove(function(cursor){
        $("#console").html(cursor.pageX+":"+cursor.pageY);
    });
    $(document).mousemove(function(cursor){
        $("#console").html(cursor.pageX+":"+cursor.pageY);
    });

.contents().find("body")抓取iframe内的内容,.mousemove()可用于添加事件监听器

测试HTML ...

<div id="console"></div>

2
投票

您应该通过将父级document事件绑定与document.getElementById('iFrameId').contentDocument事件相结合来查看,使您可以访问iFrame内容元素。

https://stackoverflow.com/a/38442439/2768917

function bindIFrameMousemove(iframe){
    iframe.contentWindow.addEventListener('mousemove', function(event) {
        var clRect = iframe.getBoundingClientRect();
        var evt = new CustomEvent('mousemove', {bubbles: true, cancelable: false});

        evt.clientX = event.clientX + clRect.left;
        evt.clientY = event.clientY + clRect.top;

        iframe.dispatchEvent(evt);
    });
};

bindIFrameMousemove(document.getElementById('iFrameId'));

1
投票

虽然指针事件:无;在框架的样式可以解决这个问题,但它禁用iframe中的任何其他事件,我的解决方案是切换值,如:

{{pointer-events : isMoving? 'none' : 'all' }}

0
投票

这适用于我将父文档事件绑定与document.getElementById('iFrameId').intentDocument事件相结合,使您可以访问iFrame内容元素。

https://stackoverflow.com/a/38442439/2768917

function bindIFrameMousemove(iframe){
    iframe.contentWindow.addEventListener('mousemove', function(event) {
        var clRect = iframe.getBoundingClientRect();
        var evt = new CustomEvent('mousemove', {bubbles: true, cancelable: false});

        evt.clientX = event.clientX + clRect.left;
        evt.clientY = event.clientY + clRect.top;

        console.log(evt);
        iframe.dispatchEvent(evt);
    });
};

bindIFrameMousemove(document.getElementById('iFrameId'));
© www.soinside.com 2019 - 2024. All rights reserved.