javascript使用严格的doctype创建iframe

时间:2013-01-06 19:52:54

标签: javascript iframe doctype

我正在构建一个可嵌入其他网站的小部件。该小部件是使用document.write()创建的iframe,但我不知道如何使用javascript应用iframe文档类型。

这是我的代码:

document.write("<iframe scrolling=\"no\" frameborder=\"0\">");
document.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"   \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
document.write("<html>");
document.write("<head></head><body></body>");
document.write("</html>");
document.write("</iframe>");
document.write("</div>");

iframe已创建但我未应用doctype。 有没有办法做到这一点?

由于

2 个答案:

答案 0 :(得分:13)

为了写入iframe,您首先需要创建它,将其附加到文档中,然后到达其内部以获取其contentDocument的句柄。

以下是一些示例代码:

// create the iframe and attach it to the document
var iframe = document.createElement("iframe");
iframe.setAttribute("scrolling", "no");
iframe.setAttribute("frameborder", "0");
document.body.appendChild(iframe);

// find the iframe's document and write some content
var idocument = iframe.contentDocument;
idocument.open();
idocument.write("<!DOCTYPE html>");
idocument.write("<html>");
idocument.write("<head></head>");
idocument.write("<body>this is the iframe</body>");
idocument.write("</html>");
idocument.close();

// now have a look at your creation in the console
console.log(idocument);

请参阅此jsfiddle

答案 1 :(得分:1)

您还可以使用HTML5 srcdoc属性来指定iframe的内容。

document.getElementById('myFrame').srcdoc = "<!DOCTYPE html PUBLIC....";

您必须检查浏览器是否支持srcdoc

相关问题