CodeMirror是一个JavaScript组件,可在浏览器中提供代码编辑器。它具有丰富的编程API,并专注于可扩展性。

官网:http://codemirror.net/

百科:https://en.wikipedia.org/wiki/CodeMirror

关于cm(codemirror)的使用方法不做具体描述了,引入css、js,初始化textarea等,文章案例将统一使用以下代码(案例中设置的是初始化编辑器部分):

<!DOCTYPE html>
<html>
<head>
	<title>CodeMirror Demo</title>
    <link href="codemirror.css" rel="stylesheet">
</head>
<body>
    <div>
        <textarea class="form-control" rows="20" id="CodeMirrorArea"></textarea>
    </div>
    <script src="codemirror.js"></script>
    <script src="codemirror/mode/javascript/javascript.js"></script>
    <!--初始化编辑器部分-->
</body>
</html>

案例一

环境:websocket

描述:只读模式回显websocket数据,自动跳转到编辑器底部

    <script type="text/javascript">
    $(document).ready(function() {
        var editor = CodeMirror.fromTextArea(document.getElementById("CodeMirrorArea"), {
            lineNumbers: true,
            matchBrackets: true,
            styleActiveLine: true,
            readOnly: true,        //只读模式
            lineWrapping: true,    //长文字换行
            scrollbarStyle: null,  //滚动条样式
            cursorBlinkRate: -1,   //隐藏光标
        });
        editor.setSize('auto','360px');
        // 在最后一行中追加codemirror编辑器内容
        function updateCodeMirror(data){
            var doc = editor.getDoc();
            var cursor = doc.getCursor(); // gets the line number in the cursor position
            var line = doc.getLine(cursor.line); // get the line contents
            var pos = { // create a new object to avoid mutation of the original selection
                line: editor.lastLine(), //获取最后一行,也可以获取当前光标行:cursor.line
                ch: line.length - 1 // set the character position to the end of the line
            }
            doc.replaceRange('\n'+data+'\n', pos); // adds a new line
            // 跳转到编辑器底部
            editor.execCommand("goDocEnd");
        }
        // 跳转到编辑器顶部
        // editor.execCommand("goDocStart");
     });
     </script>

·End·