1

I want to build a simple online editor like plunker. Does anyone know how to accomplish the live preview, once several files (.html, .css, .js, .json) have been uploaded?

Taking JSBin as example, there are only 1 html text, 1 css text and 1 js text, so it is simple: we just need to construct one complete html file from these texts and use Document.write().

However, how do editors such as plunker, brackets, vscode do live preview? Do they also construct one complete file by themselves or they use some third-party tools?

4

1 回答 1

2

实时预览非常简单。只需将页面上某个区域的 HTML 替换为用户提供的 HTML。实际上,iframe出于安全目的,您可能希望在沙盒中执行此操作。

下面的代码片段展示了如何做到这一点,全部在 JavaScript 中。尝试运行代码段并在框中输入。

function doLivePreview() {
  $("#output").html($("#source").val());
}

$(function() {
  doLivePreview();
  $("#source").on("input", doLivePreview);
});
#source {
  float: left;
}

#output {
  float: left;
  border: 1px solid #AAA;
  margin-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="source" cols="50" rows="8">
Type to see a live preview
<br/>
<a href="https://www.google.com">Google<a>
</textarea>
<div id="output">
</div>

于 2017-02-08T22:37:15.793 回答