是否可以向 iframe 添加事件监听器?我试过这段代码,但它似乎不起作用:
document.getElementsByTagName('iframe')[0].contentWindow.window.document.body.addEventListener('afterLayout', function(){
console.log('works');
});
我也刚刚尝试使用通过 id 获取元素并通过我正在使用的 JavaScript 框架添加我的监听器,如下所示:
Ext.fly("iframeID").addListener('afterLayout', function(){ alert('test'); });
我可以调用 iframe 中的函数,所以我认为安全性不是问题。有任何想法吗?
最佳答案
我从未尝试过处理“afterLayout”事件,但需要更多浏览器兼容的代码
您将使用 (iframe.contentWindow || iframe.contentDocument
) 而不是 iframe.contentWindow
。
尝试类似的东西
var iframe = document.getElementsByTagName('iframe')[0],
iDoc = iframe.contentWindow // sometimes glamorous naming of variable
|| iframe.contentDocument; // makes your code working :)
if (iDoc.document) {
iDoc = iDoc.document;
iDoc.body.addEventListener('afterLayout', function(){
console.log('works');
});
};
希望对您有所帮助。
关于javascript - 向 iframe 添加事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1394262/