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页面中编写好代码:
!--选择脚本编码代码-- div input type="radio" name="script_once_type" id="script_once_type1" checked shell input type="radio" name="script_once_type" id="script_once_type2" bat input type="radio" name="script_once_type" id="script_once_type3" python /div !--选择脚本风格代码-- div 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" #!/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插件官网: 查看其配置文档。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持凡科!