我有一个javascript应用程序,它为文档添加了一个mousemove监听器。问题:当鼠标移动到iframe上时,不会调用该函数。
有没有办法将这些事件传递给根文档?
如果iframe中的文档位于同一document.domain中,则可以非常轻松地完成此操作。
如果你有相同的document.domain,你也必须在iframe中设置一个mousemove监听器,并将值传递给父页面。
如果文档不在同一个document.domain上,它会变得非常复杂,你需要iframes页面来运行设置mousemove事件监听器的javascript本身。然后你可以进行如下所述的跨框架通信:http://softwareas.com/cross-domain-communication-with-iframes
否则,由于浏览器强制执行的原始策略相同,您运气不佳。
把pointer-events: none;
放在框架的样式中。
我自己遇到了这个问题,发现这个解决方案效果很好而且非常简单!
我刚才遇到了同样的问题,我想出了这个问题:
$("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>
您应该通过将父级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'));
虽然指针事件:无;在框架的样式可以解决这个问题,但它禁用iframe中的任何其他事件,我的解决方案是切换值,如:
{{pointer-events : isMoving? 'none' : 'all' }}
这适用于我将父文档事件绑定与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'));