CodeMirror在線代碼編輯器使用


CodeMirror官網地址為:https://codemirror.net/

CodeMirror作為一款代碼編輯器,其應用場景主要是在線網站寫代碼。
如現在的leetcode、洛谷、code-vs等都使用不同的代碼編輯器。

代碼示例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>測試</title>
        <link rel="stylesheet" type="text/css" href="../fonticon/css/codemirror.css"/>
        <link rel="stylesheet" href="../fonticon/css/codemirror/theme/midnight.css">
    </head>
    <body>
        <textarea name="code" id="editorArea" style="display:none"></textarea>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous">
        </script>
        <script src="../js/codemirror.js"></script>
        <script>
            
            var editor = CodeMirror.fromTextArea(document.getElementById("editorArea"), {
                lineNumbers: true,        //是否在編輯器左側顯示行號
                matchBrackets: true,      // 括號匹配
                mode: "text/x-c++src",    //C++
                indentUnit:4,             // 縮進單位為4
                indentWithTabs: true,     //
                smartIndent: true,        //自動縮進,設置是否根據上下文自動縮進(和上一行相同的縮進量)。默認為true。
                styleActiveLine: true,       // 當前行背景高亮
                theme: 'midnight',         // 編輯器主題
        
            });
    
            editor.setSize('600px','400px'); //設置代碼框大小
            

        </script>
    </body>
</html>

效果圖:

 

 

關於如何給代碼框中賦值和取值,可使用如下方法:

editor.setValue(""); //賦值


editor.getValue(); //取值

上述只是一個簡單的示例,更多知識還請參考官方網站對應的文檔。


免責聲明!

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



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