也从iframe接收mousemove事件

18

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

是否有一种方法可以将这样的事件传递到根文档?

6个回答

43
在框架的样式中加入pointer-events: none;
我自己也遇到过这个问题,发现这个解决方案非常好用而且很简单!

11
是的,这是正确的,但这将禁用所有其他事件,比如滚动或高亮。 - Ashraf
@Ashraf,pointer-events:none; 运行良好,但它会禁用 iframe 加载文档上的所有其他事件,你是如何解决这个问题的?谢谢。 - Sujithrao
7
我在我的 CSS 中声明了 body.dragging iframe {pointer-events: none;},并且只有当我需要触发鼠标移动时才设置了 document.body.classList.add('dragging'); - Kyle

6
你应该结合父级document事件绑定和document.getElementById('iFrameId').contentDocument事件查看,这样可以让你获取iFrame内容元素的访问权限。
参考链接:https://dev59.com/L2035IYBdhLWcg3wErvM#38442439
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'));

非常感谢,你在这里帮了我很多的忙。 - dieterh

4
如果iframe中的文档与当前文档具有相同的document.domain,则可以很容易地实现。如果你有相同的document.domain,你还需要在iframe中设置mousemove监听器,并将值传递给父页面。如果文档没有相同的document.domain,则变得更加复杂,你需要在iframes页面上运行javascript来设置mousemove事件监听器。然后你可以像这里描述的那样进行跨框架通信:http://softwareas.com/cross-domain-communication-with-iframes否则,由于浏览器执行的同源策略,你将无法实现。

1
好的,那么我必须使用一个透明的 div,它覆盖在 iframe 上面。 - Van Coding
我喜欢透明的div的想法,但是你如何将鼠标事件从iframe传回父级呢? - Redtopia
只需将其作为参数传递给您选择的函数调用即可 :) - Martin Jespersen

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

虽然在框架样式中使用pointer-events: none;可以解决这个问题,但它会禁用iframe中的任何其他事件。我的解决方案是切换值,例如:

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

1
这对我很有效,结合父文档事件绑定和document.getElementById('iFrameId').contentDocument事件,可以让您访问iFrame内容元素。

https://dev59.com/L2035IYBdhLWcg3wErvM#38442439

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'));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接