codeMirror插件使用讲解

codeMirror是一款十分强大的代码编辑插件,提供了十分丰富的API,最近在项目中用到了这款插件,于是在这里给大家分享下使用方法和心得。具有一定的参考价值,下面跟着小编一起来看下吧

codeMirror是一款十分强大的代码编辑插件,提供了十分丰富的API,最近在项目中用到了这款插件,于是在这里给大家分享下使用方法和心得:

codeMirror调用非常方便

首先在页面中载入插件CSS及JS文件

<link href="https://www.jb51.net/static/codemirror/lib/codemirror.css" > <script src="https://www.jb51.net/static/codemirror/lib/codemirror.js"></script>

同时加载你所需要使用的脚本JS及风格样式CSS文件,如下举例:

<link href="https://www.jb51.net/static/codemirror/theme/3024-night.css"> <link href="https://www.jb51.net/static/codemirror/theme/erlang-dark.css"> <script src="https://www.jb51.net/static/codemirror/mode/shell/shell.js"></script> <script src="https://www.jb51.net/static/codemirror/mode/perl/perl.js"></script> <script src="https://www.jb51.net/static/codemirror/mode/python/python.js"></script>

注意文件的放置位置

下一步在html页面中编写好代码:

<!--选择脚本编码代码--> <div> <input type="radio" checked> shell <input type="radio"> bat <input type="radio"> python </div> <!--选择脚本风格代码--> <div> <select> <option>default</option> <option>3024-night</option> <option selected>erlang-dark</option> </select> </div> <!--textarea--> <textarea> #!/bin/sh </textarea> <textarea> #!/usr/bin/env python # -*- coding: utf8 -*- </textarea>

调用关键代码如下:

var editor = CodeMirror.fromTextArea($("#script_once_code")[0], { //script_once_code为你的textarea的ID号 lineNumbers: true,//是否显示行号 mode:"shell", //默认脚本编码 lineWrapping:true, //是否强制换行 });

JS配置代码如下:

//选择界面风格JS $('#select').change(function(){ var theme = $('#select').val(); editor.setOption("theme", theme); //editor.setOption()为codeMirror提供的设置风格的方法 }); //选择脚本类型JS var txt1=$("#script_once_code").val(); var txt2=''; var txt3=$("#code2").val(); $(".ck-code").click(function(){ var txt=editor.getValue(); //editor.getValue()获取textarea中的值 var lang=$(this).prop("id"); if(lang=="script_once_type1") { editor.setOption("mode","shell");//editor.setOption()设置脚本类型 editor.setValue(txt1);// editor.setValue()设置textarea中的值 } else if(lang=="script_once_type2") { editor.setOption("mode","perl"); editor.setValue(txt2); } else { editor.setOption("mode","python"); editor.setValue(txt3); } });

最终界面如下:

codeMirror插件使用讲解

如需配置更多参数,可以访问codeMirror插件官网: 查看其配置文档。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwdjwd.html