0

我已经使用下面的方法来查看修改 textarea 区域时的输出,它工作正常。但是我想使用 Codemirror 作为 textarea,当我在 codemirror textarea 中插入任何数据时,输出应该出现 div 。

<script type="text/javascript">
function updateDisplay() {
document.getElementById("code").innerHTML =      document.getElementById("entry").value;
}
</script>

<textarea onkeyup="updateDisplay();" name="entry" id="entry" cols="1000" rows="500"></textarea>
<div name="code" id="code" ></div>

代码镜像

 <link rel="stylesheet" href="http://codemirror.net/lib/codemirror.css">
<script src="http://codemirror.net/lib/codemirror.js"></script>
<script src="http://codemirror.net/mode/xml/xml.js"></script>
<script src="http://codemirror.net/mode/javascript/javascript.js"></script>
<script src="http://codemirror.net/mode/css/css.js"></script>
<script src="http://codemirror.net/mode/htmlmixed/htmlmixed.js"></script>



<textarea id="code" name="code">
<html style="color: green">
  <!-- this is a comment -->

<style type="text/css">
  h1 {font-family: comic sans; color: #f0f;}
  div {background: yellow !important;}
  body {
    max-width: 50em;
    margin: 1em 2em 1em 5em;
  }
</style>
</head>
 <body>

<script>
  function jsFunc(arg1, arg2) {
    if (arg1 && arg2) document.body.innerHTML = "achoo";
  }
 </script>
 </body>
</html>
</textarea></form>
<script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", tabMode: "indent"});
</script>

4

2 回答 2

0

您需要将 onChange 传递给 CodeMirror,尝试以下代码:

<script>
    var editor = CodeMirror.fromTextArea(document.getElementById("entry"), {
        mode: "text/html",
        lineNumbers: true,
        onKeyEvent: function(editor) {
              document.getElementById("code").innerHTML = editor.getValue();
        }
    });
</script>

演示:http: //jsfiddle.net/ZbHGY/

于 2013-01-31T04:42:02.507 回答
0

以下适用于 Codemirror v5.x

监听编辑器的“更改”事件,然后调用 save() 方法将编辑器的值传输到原始文本区域。

<script>
  var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "text/html", tabMode: "indent"});
  editor.on("change", function(cm){ cm.save() })
</script>
于 2017-11-17T15:31:46.953 回答