ace.js实现IDE多标签代码编辑器
ace.js是一款强大的代码编辑器,支持110种开发语言,安装官方的说法,可以媲美本地的开发工具vscode等,今天我们来演示一下如何使用ace.js来实现一个多标签的代码编辑器功能,先看效果:
原理其实很简单,就是在创建ace的时候,创建一个tab标签, 并保存到全局变量中,如下:
editor_arr.push({ "fileid": fileid, "editor": editor, "editorid": editorid, "tabid": "tab" + fileid, });
我们来看看代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>BFW NEW PAGE</title> <script id="bfwone" data="dep=jquery.17&err=0" type="text/javascript" src="http://repo.bfw.wiki/bfwrepo/js/bfwone.js"></script> <script type="text/javascript"> var editor_arr = []; bready(function() { $("#addnewbtn").click(function() { openeditor(Math.random()*100000000000000000, "unamed"); }); }); function showeditor(fileid) { console.log(fileid); $("#bfweditor pre").hide(); $("#file_tab ul li").removeClass("file_selected"); if (editor_arr.length > 0) { for (var i = 0; i < editor_arr.length; i++) { if (fileid == editor_arr[i].fileid) { $("#" + editor_arr[i].tabid).addClass("file_selected"); $("#" + editor_arr[i].editorid).show(); return editor_arr[i].editor; } } } return null; }; function openeditor(fileid, filename) { var editor = showeditor(fileid); if (editor != null) { return; } $("#file_tab ul li").removeClass("file_selected"); $("#addnewbtn").before("<li fileid='"+fileid+"' id='tab" + fileid + "' class='file_selected' title='" + filename + "'><span id='filechanged_" + fileid + "'></span><i class='filename_"+fileid+"'>" + filename + "</i><span class='tab_close' fileid='"+fileid+"' id='close" + fileid + "'>×</span></li>"); $("#tab" + fileid).click(function() { showeditor(fileid); }); var editorid = "edi" + fileid; $("#bfweditor pre").hide(); $("#bfweditor").append("<pre id='" + editorid + "' ></pre>"); use(["ace"], function() { var editor = ace.edit(editorid); editor.$blockScrolling = Infinity; editor.session.setMode("ace/mode/html"); editor.setOption("wrap", "free"); editor.setValue("hello"); editor.clearSelection(); editor_arr.push({ "fileid": fileid, "editor": editor, "editorid": editorid, "tabid": "tab" + fileid, }); }); }; </script> <style> .file_selected { background-color: #000000; color: white; font-weight: bold; } #file_tab { height: 36px; clear: both; overflow: hidden; background: #272727; } #file_tab ul { list-style: none; padding: 0; margin: 0; } #file_tab ul li { height: 36px; display: block; line-height: 32px; padding: 0 17px; color: grey; float: left; cursor: pointer; } #file_tab ul li:hover { font-weight: bold; background: grey; color: black; } #bfweditor { width: 100%; height: 100%; background: black; padding: 0; } #bfweditor pre { width: 100%; height: 100%; margin: 0; } .tab_close { display: none; padding-left: 5px; cursor: pointer; } </style> </head> <body> <div id="file_tab" class="scrollbar"> <ul> <li class="addnew" title="新建文件" style="font-weight: bold; font-size: 18px;" id="addnewbtn">+</li> </ul> </div> <div id="bfwcont"> <div id="bfweditor" class="bfw-s-row-100"> </div> </div> </body> </html>
网友评论0