iframe:如何显示原始(纯文本)html?

2022-02-25 00:00:00 iframe javascript html nuxt.js

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

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

我已尝试这样显示它:

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

但是它没有起作用。它显示粗体";Hello world&qot;文本。

我正在使用Nuxt.js。

我错过了什么?


解决方案

无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>

相关文章