codeMirror插件使用講解
codeMirror是一款十分強大的代碼編輯插件,提供了十分豐富的API,最近在項目中用到了這款插件,于是在這里給大家分享下使用方法和心得:
codeMirror調(diào)用非常方便
首先在頁面中載入插件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頁面中編寫好代碼:
<!--選擇腳本編碼代碼-->
<div class="controls">
<input class="ck-code" type="radio" name="script_once_type" id="script_once_type1" checked> shell
<input class="ck-code" type="radio" name="script_once_type" id="script_once_type2"> bat
<input class="ck-code" type="radio" name="script_once_type" id="script_once_type3"> python
</div>
<!--選擇腳本風格代碼-->
<div class="controls">
<select id='select'>
<option>default</option>
<option>3024-night</option>
<option selected>erlang-dark</option>
</select>
</div>
<!--textarea-->
<textarea id="script_once_code">
#!/bin/sh
</textarea>
<textarea id="code2" class="hide">
#!/usr/bin/env python
# -*- coding: utf8 -*-
</textarea>
調(diào)用關(guān)鍵代碼如下:
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);
}
});
最終界面如下:

如需配置更多參數(shù),可以訪問codeMirror插件官網(wǎng):http://codemirror.net/ 查看其配置文檔。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
webpack教程之webpack.config.js配置文件
本篇文章主要介紹了webpack教程之webpack.config.js配置文件 ,具有一定的參考價值,有興趣的可以了解一席2017-07-07
基于JavaScript實現(xiàn)每日簽到打卡軌跡功能
這篇文章主要為大家詳細介紹了基于JavaScript實現(xiàn)每日簽到打卡軌跡功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-11-11
網(wǎng)頁禁用右鍵實現(xiàn)代碼(JavaScript代碼)
網(wǎng)頁禁用右鍵的代碼,我們可以不少網(wǎng)站在使用,讓別人復制什么的麻煩,但破解方法也比較簡單。這里就不說了,如果想知道的可以參考腳本之家以前發(fā)布的文章。2009-10-10
JavaScript腳本語言是什么_動力節(jié)點Java學院整理
JavaScript是什么?這篇文章主要介紹了一種廣泛用于客戶端Web開發(fā)的腳本語言JavaScript,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
JS實現(xiàn)獲取漢字首字母拼音、全拼音及混拼音的方法
這篇文章主要介紹了JS實現(xiàn)獲取漢字首字母拼音、全拼音及混拼音的方法,涉及針對ChinesePY.js插件的使用及事件響應相關(guān)操作技巧,需要的朋友可以參考下2017-11-11

