清除现有的 iframe 内容

clear existing iframe contents

本文关键字:iframe 内容 清除      更新时间:2023-09-26

我有一个文件列表。当我单击它们时,内容显示在框架内。我遇到的问题是:当我打开一个文件并移动到下一个文件时(如果文件更大,则需要一些时间来加载),旧文件的内容仍然显示在 iframe 中。一旦我单击下一个文件,我想清除iframe中旧文件的内容,同时它正在加载,我可以显示加载指示器。

为了清除iframe中的内容,我尝试了一些方法,但没有成功。你能告诉我这个吗

我的网页

<div id="result">
 <div style="overflow: auto;" id="testIframeBox">
 <iframe id="testiframe" name="testIframe" onload="">iFramenot supported</iframe></div>
</div>

我使用 location.replace 显示单击的文件

window.frames['testIframe'].location.replace(URL+"&download=1&inline=1&resourceId="+resourceId+"&time=" + Date.now());

要清除内容:

if(document.getElementById('testiframe'))
    {
    var frame = document.getElementById("testIframe"),
    frameDoc = frame.contentDocument || frame.contentWindow.document;
    frameDoc.documentElement.innerHTML="";
    }

在填充内容之前,我还尝试用加载指示器替换内容:

window.frames['testIframe'].location.replace('div class="loading-animation"></div>');

据我了解,您的问题分为两部分:

  1. 。要清除 iframe 中的内容...

答案很简单,您可以使用iframesrc 属性来控制其内容。普遍接受的做法是为src分配一个about:blank,使其加载浏览器的默认空白文档。

只有当您在iframe中加载的文档位于同一域中时,才应使用contentDocument,否则跨域安全性会阻止您的尝试。

  1. ..在填充内容之前,我尝试用加载指示器替换内容。.

这很棘手。 iframe 上的load事件确实会在浏览器中一致地触发,但这并不意味着文档已准备就绪。 DOMContentLoaded在跨浏览器的实现中是片状的。在我使用的浏览器中,至少Chrome无法触发它。 DOMFrameContentLoaded事件moz特定的,只有 Firefox 会触发它。

看看这个: 如何正确地从XUL iframe接收DOMContentLoaded事件?

您的一种选择是使用 jQuery 并依赖其 on.("load") 处理程序,它可以为您提供近乎一致的结果。但是,正如我从你的问题中看到的那样,你没有使用jQuery并依赖于普通的Javascript。在这里,IMO 对您来说最便宜的选择是处理load事件并使用setTimeout注入faux延迟来模拟加载。以下代码片段将使您清楚。

片段

document.getElementById("a1").addEventListener("click", load);
document.getElementById("a2").addEventListener("click", load);
document.getElementById("testiframe").addEventListener("load", loaded);
function load() {
    var lnk = this.innerText;
    var iframe = document.getElementById("testiframe");
    iframe.src = "about:blank";
    document.getElementById("loader").style.display = "block";
    setTimeout(function() {
        iframe.src = lnk;    /* small delay to avoid successive src assignment problems */
    }, 500);
}
function loaded() {
    /* faux delay to allow for content loading */
    setTimeout(function() {
        document.getElementById("loader").style.display = "none";
    }, 1000);
    
}
div#testIframeBox {
    width: 320px; height: 240px;
    position: relative;    
}
iframe {
    width: 100%; height: 100%;
    position: absolute;    
    top: 0px; left: 0px;
}
div#testIframeBox > div {
    position: absolute; 
    top: 16px; left: 16px;
    padding: 8px;
    background-color: yellow;
    display: none;
}
<div> 
    <a href="#" id="a1">http://jquery.com</a>
    &nbsp;|&nbsp;
    <a href="#" id="a2">http://example.com</a>
</div>
<hr />
<div id="result">
    <div id="testIframeBox">
        <iframe id="testiframe" name="testIframe"></iframe>
        <div id="loader">Loading...</div>
    </div>
</div>