您的位置:首页 > Web前端 > JavaScript

codeMirror插件使用

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

codeMirror调用非常方便

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

    <link href="/static/codemirror/lib/codemirror.css" rel="stylesheet" >

  <script src="/static/codemirror/lib/codemirror.js"></script>

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

  <link href="/static/codemirror/theme/3024-night.css" rel="stylesheet">

  <link href="/static/codemirror/theme/erlang-dark.css" rel="stylesheet">

    <script src="/static/codemirror/mode/shell/shell.js"></script>

    <script src="/static/codemirror/mode/perl/perl.js"></script>

    <script src="/static/codemirror/mode/python/python.js"></script>

注意文件的放置位置

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

1 <!--选择脚本编码代码-->
2 <div class="controls">
3     <input class="ck-code" type="radio" name="script_once_type" id="script_once_type1" checked> shell
4      <input class="ck-code" type="radio" name="script_once_type" id="script_once_type2"> bat
5      <input class="ck-code" type="radio" name="script_once_type" id="script_once_type3"> python
6 </div>
7
8 <!--选择脚本风格代码-->
9 <div class="controls">
10     <select id='select'>
11          <option>default</option>
12          <option>3024-night</option>
13          <option selected>erlang-dark</option>
14     </select>
15 </div>
16
17 <!--textarea-->
18 <textarea id="script_once_code">
19     #!/bin/sh
20 </textarea>
21 <textarea id="code2" class="hide">
22     #!/usr/bin/env python
23     # -*- coding: utf8 -*-
24 </textarea>


 

调用关键代码如下:

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


 

JS配置代码如下:

1 //选择界面风格JS
2 $('#select').change(function(){
3      var theme = $('#select').val();
4          editor.setOption("theme", theme); //editor.setOption()为codeMirror提供的设置风格的方法
5  });
6
7 //选择脚本类型JS
8 var txt1=$("#script_once_code").val();
9 var txt2='';
10 var txt3=$("#code2").val();
11 $(".ck-code").click(function(){
12        var txt=editor.getValue(); //editor.getValue()获取textarea中的值
13        var lang=$(this).prop("id");
14        if(lang=="script_once_type1") {
15                editor.setOption("mode","shell");//editor.setOption()设置脚本类型
16                    editor.setValue(txt1);// editor.setValue()设置textarea中的值
17        }
18        else if(lang=="script_once_type2") {
19                editor.setOption("mode","perl");
20                editor.setValue(txt2);
21        }
22        else {
23                editor.setOption("mode","python");
24                editor.setValue(txt3);
25
26        }
27 });


 

最终界面如下:



如需配置更多参数,可以访问codeMirror插件官网:http://codemirror.net/ 查看其配置文档。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript