这是一个基本的 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,但您不能使用 JavaScriptconst或let变量,因为一旦您编辑插入的代码,它就会抛出以下语法错误:
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为 …