相关疑难解决方法(0)

iframe 文档写入不会更新 JavaScript

这是一个基本的 HTML 编辑器:

textarea,
iframe {
  width: 400px;
  height: 300px;
}
Run Code Online (Sandbox Code Playgroud)
<textarea></textarea>
<iframe></iframe>
Run Code Online (Sandbox Code Playgroud)
var textarea = document.querySelector('textarea');

function preview() {
  var iframeDoc = document.querySelector('iframe').contentDocument;
  iframeDoc.open();
  iframeDoc.write(textarea.value);
  iframeDoc.close();
}

textarea.addEventListener('input', preview);
Run Code Online (Sandbox Code Playgroud)

演示版

它会更新您放入的 HTML 和 CSS textarea,但您不能使用 JavaScriptconstlet变量,因为一旦您编辑插入的代码,它就会抛出以下语法错误:

Identifier * has already been declared

要明白我的意思,请将以下示例代码插入到textarea

<!doctype html>
<html lang="en">
<head>
  <title>Sample Code</title>
</head>
<body>
  <p>Hello!</p>
  <script>
    const p = document.querySelector('p');
    p.style.color = 'blue';
  </script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

现在改变Hello!Hello, world!blue为 …

html javascript iframe

7
推荐指数
2
解决办法
668
查看次数

标签 统计

html ×1

iframe ×1

javascript ×1