【ace.js】基于JS的代码带高亮编辑器

2018-01-17  本文已影响0人  眠九

源码:
ace.js - https://link.jianshu.com/?t=https://github.com/ajaxorg/ace-builds.git
官网及API:
ace.js - https://link.jianshu.com/?t=https://github.com/ajaxorg/ace

在项目中只使用了它的代码高亮功能,因为到目前版本,它支持了超过120多种的语法高亮,超过20多种主题等,在编辑器方面也支持多种操作,包括提示等,算是一个基于web端的代码编辑器了。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style type="text/css" media="screen">
        .ace_editor {
            /*position: relative !important;*/
            border: 1px solid lightgray;
            border-radius:5px;
            margin: auto;
            height: 800px;
            width: 80%;
        }
    </style>
</head>
<body>
<div id="editor"></div>
<script src="ace-builds-master/src/ace.js"></script>
<script src="ace-builds-master/src-noconflict/ext-language_tools.js"></script>
<script>
    //引入语言工具
    ace.require("ace/ext/language_tools");
    const editor = ace.edit("editor");
    //选择主题
    editor.setTheme("ace/theme/twilight");
    //选择语言
    editor.session.setMode("ace/mode/javascript");
    //各项设置
    editor.setOptions({
        enableBasicAutoCompletion : true,
        enableSnippets : true,
        enableLiveAutocompletion : true
    });

    //预设值
    if (typeof ace == "undefined" && typeof require == "undefined") {
        document.body.innerHTML = "<p style='padding: 20px 50px;'>couldn't find ace.js file, <br>"
            + "to build it run <code>node Makefile.dryice.js full<code>"
    } else if (typeof ace == "undefined" && typeof require != "undefined") {
        require(["ace/ace"], setValue)
    } else {
        require = ace.require;
        setValue()
    }

    function setValue() {
        require("ace/lib/net").get(document.baseURI, function(t){
            var el = document.getElementById("editor");
            el.env.editor.setValue(t, 1);
        })
    }
</script>
</body>
</html>

所支持的功能,在官方提供的demo里都有,具体的设置参数可翻看API。


在浏览器中显示的效果
上一篇下一篇

猜你喜欢

热点阅读