我想创建一个可以编写和预览网站的网站。问题是我想在 iframe 中预览它,因为这样网站就不会受到 iframe 周围的 HTML 代码的影响。
有没有办法在 iframe 标记中显示网页,并使用字符串作为源而不是 URL?
This它应该是这样的(只是一个 iframe)。
<textarea onkeyup="document.getElementById("body").innerHTML=this.value;"></textarea>
<div id="body"></div>
事实上,JSFiddle 也是这样做的,所以一定有办法。有想法吗?
最佳答案
可以修改 src
指定的文档内容属性,使用contentWindow.document
。所以,假设您有 <textarea>
对于您想要预览的标记,您可以执行以下操作:
编辑文档:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Edit iframe example</title>
<style>
.editors, .preview { float: left; display: block; }
.editors { width: 500px; margin-right: 25px; }
.editors textarea { width: 100%; height: 300px; }
.preview { width: 800px; }
.preview iframe { width: 100%; height: 800px; }
</style>
</head>
<body>
<div class="editors">
<p>
<label>CSS</label>
</p>
<p>
<textarea id="preview-editor-CSS" onkeyup="updatePreviewCSS(this)"></textarea>
</p>
<p>
<label>HTML</label>
</p>
<p>
<textarea id="preview-editor-HTML" onkeyup="updatePreviewHTML(this)"></textarea>
</p>
</div>
<div class="preview">
<iframe id="preview" src="preview.html"></iframe>
</div>
<script>
function updatePreviewHTML(elem) {
var frame = document.getElementById('preview');
var content = elem.value;
frame.contentWindow.document.body.innerHTML = content;
}
function updatePreviewCSS(elem) {
var frame = document.getElementById('preview');
var content = elem.value;
frame.contentWindow.document.getElementsByTagName('style')[0].innerHTML = content;
}
</script>
</body>
</html>
“预览”文档:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Preview iframe example</title>
<style></style>
</head>
<body>
</body>
</html>
我只在本地 Firefox 31 上尝试过此操作,所以买者自负。
关于javascript - 使用具有可编辑网站的 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25295563/