使用 JavaScript 创建 IFRAME
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8726455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating an IFRAME using JavaScript
提问by Tim
I have a webpage hosted online and I would like it to be possible that I could insert an IFRAME onto another webpage using some JavaScript.
我有一个在线托管的网页,我希望可以使用一些 JavaScript 将 IFRAME 插入到另一个网页上。
How would this be the best way possible, that I just add my webpage URL to the JavaScript and that it work on all browsers?
这怎么可能是最好的方法,我只是将我的网页 URL 添加到 JavaScript 并且它可以在所有浏览器上运行?
Thanks
谢谢
回答by Hemant Metalia
You can use:
您可以使用:
<script type="text/javascript">
function prepareFrame() {
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "http://google.com/");
ifrm.style.width = "640px";
ifrm.style.height = "480px";
document.body.appendChild(ifrm);
}
</script>
also check basics of the iFrame element
还要检查iFrame 元素的基础知识
回答by Ryan
It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.
将 HTML 作为模板处理比通过 JavaScript 构建节点更好(毕竟 HTML 不是 XML。)通过使用模板,然后将模板的内容附加到另一个 DIV,您可以保持 IFRAME 的 HTML 语法清晰。
<div id="placeholder"></div>
<script id="iframeTemplate" type="text/html">
<iframe src="...">
<!-- replace this line with alternate content -->
</iframe>
</script>
<script type="text/javascript">
var element,
html,
template;
element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;
element.innerHTML = html;
</script>