[英]To add event listeners to all the frames in a document
我正在研究一些需要我在文檔加載時將鼠標/鍵盤事件監聽器添加到文檔的東西。
document/window.addEventListener()
運行良好,直到我遇到Frameset / frames / iframes。
我做了一些解決方法,比如迭代框架集的所有框架並向它們添加事件監聽器。
然后我意識到在DOM之后動態加載幀。 所以我做了這樣的事情:
bindListenersToFrame: function(element){
var $ = domUtils.jQuery;
$(element).ready(function(){
if(element.tagName == "FRAMESET" || element.tagName == "BODY"){
for(var i=0; i < element.children.length; i++){
domUtils.bindListenersToFrame(element.children[i]);
}
}
if(element.tagName == "FRAME" || element.tagName == "IFRAME"){
$('iframe').load(function(){
domUtils.addListener(element);
if(element.contentDocument.documentElement){
for(var i=0; i < element.contentDocument.documentElement.children.length; i++){
domUtils.bindListenersToFrame(element.contentDocument.documentElement.children[i]);
}
}
});
}
});
}
上面的方法本質上是遞歸的,而domUtils只是一個像“addListener”這樣的方法的對象。
任何幫助將不勝感激。 謝謝。
為什么不將監聽器添加到<body>
?
$('body').click(function(e) {
console.log("clicked")
})
嘗試這個:
$('body').on('click','iframe',function(e) {
console.log("clicked");
});
我建議遞歸檢查幀並附加監聽器。 這真的不應該做,但這是唯一的方法。 請注意,由於對代碼段的沙盒限制,此代碼段無法在SO上運行。 我測試了它,它在本地工作的服務器。 我也無法找到(在有限的時間內)我正在使用的setTimeout
方法。 感覺它在頁面加載之前被應用,但我看不到這些load
事件的任何影響,所以為了顯示它是如何工作的,請檢查:
function nestedIFrameEventAttacher( iframe, event, handler ){ const content = iframe.contentDocument || (iframe.contentWindow ? iframe.contentWindow .document : iframe); const body = content.querySelector( 'body' ); body.addEventListener( event, handler ); // I have tried attaching `load` and `DOMContentLoaded` events // to the `iframe` and the `body` but none of them seemed to trigger. // This is therefor not guaranteed to work, but you can start from this. setTimeout(function(){ Array.from( body.querySelectorAll( 'iframe' ) ).forEach(iframe => { nestedIFrameEventAttacher( iframe, event, handler ); }); }, 100); } const output = document.getElementById( 'output' ) nestedIFrameEventAttacher( document, 'click', function( event ){ output.textContent = this.querySelector( 'h1' ).textContent; });
#output{ color: red; }
<div id="output">Stealie the Dog</div> <h1>Root</h1> <iframe srcdoc="<html><head></head><body><h1>Second</h1><iframe srcdoc='<html><head></head><body><h1>Deeper</h2></body></html>'></iframe></body></html>" width="100%" height="500px"></iframe>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.