我一直在寻找一种跨浏览器的方法来以编程方式设置 IFrame 的innerHTML。 (如http://roneiv.wordpress.com/2008/01/18/get-the-content-of-an-iframe-in-javascript-crossbrowser-solution-for-both-ie-and-firefox/ http://roneiv.wordpress.com/2008/01/18/get-the-content-of-an-iframe-in-javascript-crossbrowser-solution-for-both-ie-and-firefox/)。我已经编写了一些示例代码(如下),我可以让它在 Safari 和 Chrome 中运行,但不能在 Firefox 中运行。谁能帮我弄清楚我需要做什么(以便携的方式)?
<html>
<body>
<div name=FRAME2div id=FRAME2div style="position:absolute; background-color:blue; color:black; border-color:black;border-width:0; left:100px; top:40px; width:200px; height:200px; overflow:scroll; display:block; " >
</div>
<script type="text/javascript">
document.getElementById("FRAME2div").innerHTML = '<iframe border=0 id=IFRAME2 name=IFRAME2 ></iframe>';
document.getElementById("IFRAME2").contentWindow.document.body.innerHTML = '<html><body><p>NETSCAPE</p></body></html>';
</script>
</body>
</html>
在 Firefox 中,如果没有设置初始内容,框架的内容似乎无法被识别。解决这个问题最简单的方法如下代码所示:
//Note: ID is not necessary for this example
document.getElementById("FRAME2div").innerHTML = '<iframe id=IFRAME2 name=IFRAME2 ></iframe>';
var doc = frames["IFRAME2"].document;
//Trigger a page "load".
doc.open();
doc.close();
//Set innerHTML of the body tag.
doc.body.innerHTML = '<p>NETSCAPE</p>';
另一种方法包括设置src
财产给javascript:" "
,并注册一个一次性加载事件处理程序。这种方法稍微复杂一些,因此我不会更详细地描述它。
Every frame's window object can be accessed through the frame
object, by name.
因此,我建议使用以下代码:
frames['IFRAME2'].document.documentElement.innerHTML = "<body>...</body>";
document.documentElement
指文档的根元素,通常<html>
。有可能的是body
的财产document
当您调用当前代码时,尚未准备好。通过引用根元素,可以避免这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)