codeMirror插件使用講解


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/ 查看其配置文檔。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM