利用ace.js编写一个JavaScript编辑器(带智能补全)

来源:互联网 发布:netflix ribbon源码 编辑:程序博客网 时间:2024/09/21 08:16
<html lang="en">    <head>        <title>javascript编辑器</title>        <style type="text/css" media="screen">            #aaa {                 width:50%;            }            #editor {                 width:100%;                padding-bottom: 35%;            }            #iframe1{                width:100%;                background: #505050;                border:1px;            }            #rundata{                width:100%;                border:1px;            }        </style>    </head>    <body>        <div id="aaa">            <div id="editor"></div>            <div ><button id="rundata" onclick="rundata()">RUN</button></div>            <div ><iframe id="iframe1"></iframe></div>                     </div>                <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js" type="text/javascript" charset="utf-8"></script>        <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ext-language_tools.js" type="text/javascript" charset="utf-8"></script>        <script>            ace.require("ace/ext/language_tools");            var editor = ace.edit("editor");            editor.setOptions({        //      enableBasicAutocompletion: true,        //      enableSnippets: true,                enableLiveAutocompletion: true,//只能补全            });            editor.setTheme("ace/theme/monokai");//monokai模式是自动显示补全提示            editor.getSession().setMode("ace/mode/javascript");//语言            editor.setFontSize(16);        </script>        <script>            function rundata(){                  //获取输入框内的数据                  var text = document.getElementById('editor').innerText;                  // 先清空iframe                if(document.getElementById("iframe1").contentWindow.document.body!=null){                    var iframe = document.getElementById("iframe1").contentWindow.document.body.innerText = "";                }                //添加script标签,去掉开头的行号                var ctext = "<script>"+text.replace(/\d\n/g, "")+'<\/script>';                console.log(ctext);                //替换控制台打印(伪装效果)                if(ctext.indexOf("console.log")>0){                    ctext = ctext.replace("console.log", "document.write");                }                console.log(ctext);                //将输入框内的数据传给iframe                  iframe = document.getElementById('iframe1').contentDocument.write(ctext);           }                    </script>    </body></html>

效果:


ace地址:https://github.com/ajaxorg/ace-builds/