我有一个文件列表。当我点击它们时,内容显示在一个框架内。我遇到的问题是:当我打开一个文件并移动到下一个文件时(如果文件更大,加载需要一些时间),旧文件的内容仍然显示在 iframe 中。单击下一个文件后,我想清除 iframe 中旧文件的内容,同时它正在加载我可以显示加载指示器。
为了清除 iframe 中的内容,我尝试了一些方法但没有成功。你能给我一些建议吗
我的 HTML
<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>');
最佳答案
据我了解,您的问题分为两部分:
- ... To clear the contents inside iframe ...
答案很简单,您可以使用 iframe
的 src
属性来控制其内容。普遍接受的做法是将 about:blank
分配给 src
以使其加载浏览器的默认空白文档。
contentDocument
应该仅在您在 iframe
中加载的文档位于同一域中时使用,否则跨域安全会阻止您的尝试。
- ..I tried to replace the contents with loading indicator before filling the contents..
这很棘手。 iframe 上的 load
事件在浏览器中一致触发,但这并不意味着文档已准备就绪。 DOMContentLoaded
在跨浏览器的实现中不稳定。在我使用的浏览器中,至少 Chrome 无法启动它。 DOMFrameContentLoaded
事件是 moz
特定的,只有 Firefox 会触发它。
看这个:How to properly receive the DOMContentLoaded event from an XUL iframe?
您的一个选择是使用 jQuery 并依赖其 on.("load")
处理程序,这可能会为您提供几乎一致的结果。但是,正如我从您的问题中看到的那样,您没有使用 jQuery 而是依赖普通的 Javascript。在这里,IMO 最便宜的选择是处理 load
事件并使用 setTimeout
注入(inject)一个 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>
|
<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>
关于javascript - 清除现有的 iframe 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27105828/