【问题标题】:javascript create an iframe with strict doctypejavascript 创建一个具有严格文档类型的 iframe
【发布时间】:2013-01-06 19:52:53
【问题描述】:

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

这是我的代码:

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。 有没有办法做到这一点?

谢谢

【问题讨论】:

  • 恐怕这不是真的有效。 iframe 标签之间的所有元素都在原始页面中,如果浏览器不支持 iframe,则会显示出来。使用此代码得到的只是带有src="about:blank" 的 iframe。请检查:MDN: &lt;iframe&gt;.
  • @Teemu 哦.. 我明白了.. 但问题仍然存在。我用 javascript 创建了一个 inframe,我可以使用 javascript 向 iframe 添加元素。有没有办法添加文档类型?
  • 如果你的意思是,你真的“document.write()”在你的代码中body标签之间的一些元素,它们也可以在iframe中看到,这个问题将超出我的知识范围:)。
  • This post 也可能是有趣的阅读...

标签: javascript iframe doctype


【解决方案1】:

为了写入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 中查看它的工作原理。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 2018-02-28
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 2013-06-03
      相关资源
      最近更新 更多