本文主要是介绍利用ace.js编写一个JavaScript编辑器(带智能补全),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<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" οnclick="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/
这篇关于利用ace.js编写一个JavaScript编辑器(带智能补全)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!