【问题标题】:Real-Time Html editor with Javascript带有 Javascript 的实时 Html 编辑器
【发布时间】:2023-03-12 18:06:01
【问题描述】:

这是我尝试构建实时 html 编辑器的代码。在 javascript 中,我从 id=pure 的 textarea 获取文本,然后在 document.body.onkeyup 函数中,我将值传递给 id= 的 textarea编译。它根本不起作用。我想知道问题是关于 open-writeln-close 还是其他语法?

function compile() {

    var h = document.getElementById("pure");
    var compiled = document.getElementById("compiled").contentWindow.document;

     document.body.onkeyup = function(){
        compiled.open();
        compiled.writeln(h.value);
        compiled.close();
      };
    }

compile();




<div class="form-group">
  <label for="html">Write your HTML here:</label>
  <textarea class="form-control" rows="3" id="pure"></textarea><br>
    <textarea class="form-control" rows="2" id="compiled"></textarea>
</div>

【问题讨论】:

  • 我很确定您的意思是 &lt;iframe&gt; 作为编译输出。 &lt;textarea&gt; 没有 contentWindow

标签: javascript html editor real-time


【解决方案1】:

在查看您的代码后,不能 100% 确定您是什么。

但是,如果您的所有之后都有一个 TextArea,您可以放置​​ HTML 标记,然后查看预览。下面是一个例子..

var h = document.getElementById("pure");
var compiled = document.getElementById("compiled");
h.onkeyup = function() {
  compiled.innerHTML = h.value;
  pure.classList.toggle("error",
    compiled.innerHTML !== h.value); 
};
h.onkeyup();
.error {
 background-color: red;
 color: white;
}
<label for="html">Write your HTML here:</label>
<br>
<textarea class="form-control" rows="3" id="pure">
Hello <b>world</b>
</textarea><br>
<div id="compiled"></div>

【讨论】:

  • 实际上这是我正在尝试的,但我有一个问题。当您编写

    Hallo 或

    Hallo

    时,您会得到相同的结果。如果它无效,是否可以在预览时获得纯html?
  • 如果您的意思是向您显示某种错误,您只需检查保存的 HTML 并查看它是否与您的 TextArea 相同,如果不同,您就知道有错误。我更新了 Snippet,输入一些无效的 HTML,TextArea 会变红。
【解决方案2】:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="">

<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>

</div>

</body>
</html>

【讨论】:

    猜你喜欢
    • 2020-01-27
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 2016-08-15
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多