【问题标题】:iframe: How to display raw (plain text) html?iframe:如何显示原始(纯文本)html?
【发布时间】:2021-11-16 07:49:47
【问题描述】:

我想在 iframe 中将 HTML 字符串显示为原始/纯文本 HTML。

例如,显示“<b>Hello World</b>”(而不是 Hello World)。

我试过这样显示:

<iframe srcdoc="<pre><b>Hello World</b></pre>"></iframe>

但它没有用。它显示粗体“Hello world”文本。

我正在使用 Nuxt.js。

我错过了什么?

【问题讨论】:

  • 您的 iframe 内容必须是其他 html 文件。查看示例代码 => stackoverflow.com/questions/69170585/scope-issue-with-iframe/…
  • 感谢您的回复。实际上我希望能够显示来自数据库的纯 html。所以我不想创建一个单独的html文件
  • 没有单独的 HTML 文件 == 没有 iFrame
  • 看起来您的示例展示了如何在父页面和 iframe 之间进行通信的技巧。我不需要它,我只需要渲染一个带有 html 内容(作为纯文本)的 iframe。使用上面的代码,我能够呈现 iframe,它呈现 HTML 的唯一问题,而不是纯文本
  • 是的,我的例子展示了这个技巧,因为它是对这种交流的回答。但它也展示了如何将 iFrame 与您自己的内容一起使用

标签: javascript html iframe nuxt.js


【解决方案1】:

没有 iframe

<pre id="code"></pre>

<script>
  document.getElementById('code').textContent = '<b>Hello World</b>';
</script>

使用 iframe

<iframe id="codeFrame"></iframe>

<script>
  function writeToIframe(iframe, markup) {
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write('<pre id="code"></pre>');
    iframe.contentWindow.document.getElementById('code').textContent = markup;
    iframe.contentWindow.document.close();
  }

  writeToIframe(document.getElementById('codeFrame'), '<b>Hello World</b>');
</script>

【讨论】:

  • 这正是我想要的!谢谢,帮了大忙!
猜你喜欢
  • 1970-01-01
  • 2013-05-19
  • 2012-01-11
  • 2020-04-17
  • 2015-07-06
  • 2014-04-01
  • 2011-03-02
  • 2011-10-12
  • 2012-04-06
相关资源
最近更新 更多