【问题标题】:How to output result of codemirror in iframe?如何在 iframe 中输出 codemirror 的结果?
【发布时间】:2018-01-03 04:26:48
【问题描述】:

我正在尝试制作一个 HTML 代码播放器,您可以在其中输入 html 并在 iframe 中获取结果。如果我只使用 textarea 并在iframe 中输出,效果会很好。但是如果我使用代码镜像并尝试将 coremirror 值放入 iframe 它会在 iframe 中显示代码而不是显示结果。

<!DOCTYPE html>
<html>

  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="codemirror/codemirror/lib/codemirror.js"></script> 
  <link rel="stylesheet" href="codemirror/codemirror/lib/codemirror.css"/> 
  <link rel="stylesheet" href="codemirror/codemirror/theme/neo.css">

  <script src="codemirror/codemirror/mode/javascript/javascript.js"></script>   
  <script src="codemirror/codemirror/mode/css/css.js"></script>  
  <script src="codemirror/codemirror/mode/htmlmixed/htmlmixed.js"></script>  

   <script src="codemirror/codemirror/addon/hint/show-hint.js"></script>
   <script src="codemirror/codemirror/addon/hint/css-hint.js"></script>
   <link rel="stylesheet" href="codemirror/codemirror/addon/hint/show-hint.css">

  <style>
  body {
    background-color: #eee;
}
iframe{height:600px;width:400px}
</style>
  </head>

  <body>  
      <div id="codeeditor"></div>
      <iframe>Example</iframe>
      <button>RUN</button>
    <script>
       var editor = CodeMirror(document.getElementById("codeeditor"), {
    value: "<html><body><h1>Helloworld</h1></body></html>",
    mode: "css",
    theme: "neo",
    extraKeys: {"Ctrl-Space": "autocomplete"}
});
     $("button").click(function(){
          $("iframe").contents().find("body").html($("#codeeditor").html());
     })


    </script>
  </body>

</html>

【问题讨论】:

标签: javascript jquery html codemirror


【解决方案1】:

不要使用jQuery获取编辑器内容,而是使用codemirror方法getValue这样:

$("button").click(function(){     
  $("iframe").contents().find("body").html(editor.getValue());
})

【讨论】:

  • 上周我不得不切换到 ace。现在我现在也如何使用代码镜像。谢谢:)。
  • 如果你使用javascript模式最好使用doc.open/write/close
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多