ueditor里面已经继承了插入代码的功能,命令是“insertcode”, 但是插入代码的样式是这样的
通过ueditor的扩展功能,重新添加一个插入代码的功能选项。直接将下面的代码粘贴到js文件里,在ueditor之后引入即可。CODECONFIG是语言的配置项,key是下拉列表里显示的text,value是highlightjs对应的语言class,
代码中的注意点1,2,3
const CODECONFIG= {
javascript: 'javascript'
}
UE.registerUI('代码语言',function(editor,uiName){
setTimeout(() => {
//1.取ueditor所在的iframe
let document_ = window.frames['ueditor_0'].contentWindow.document;
//2.添加highlightjs所需的css,js, 这里的样式文件可以换成自己喜欢
let css = document.createElement('link');
css.rel = 'stylesheet';
css.href = 'css/agate.css'
let script = document.createElement('script');
script.src = 'util/hljs/highlight.pack.js'
document_.head.appendChild(css)
document_.head.appendChild(script)
},500)
//注册按钮执行时的command命令,用uiName作为command名字,使用命令默认就会带有回退操作
editor.registerCommand(uiName,{
execCommand:function(cmdName,value){
//3.获取选择的内容,用hljs。highlightBlock方法进行格式化,然后插入
let selectText = editor.selection.getRange().cloneContents();
var div = document.createElement('div');
div.appendChild(selectText);
hljs.highlightBlock(div);
ue.execCommand('inserthtml','<pre><code class="hljs '+CODECONFIG[value]+'">'+div.innerHTML+'</code></pre>')
},
queryCommandValue:function(){
//这里借用fontsize的查询命令
return this.queryCommandValue('insertcode')
}
});
//创建下拉菜单中的键值对,这里我用字体大小作为例子
var items = [];
for(let k in CODECONFIG){
items.push({
//显示的条目
label:k,
//选中条目后的返回值
value: CODECONFIG[k],
});
}
//创建下来框
var combox = new UE.ui.Combox({
//需要指定当前的编辑器实例
editor:editor,
//添加条目
items:items,
//当选中时要做的事情
onselect:function (t, index) {
//拿到选中条目的值
editor.execCommand(uiName, this.items[index].value);
},
//提示
title:uiName,
//当编辑器没有焦点时,combox默认显示的内容
initValue:uiName
});
editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
if (!uiReady) {
var state = editor.queryCommandState(uiName);
if (state == -1) {
combox.setDisabled(true);
} else {
combox.setDisabled(false);
var value = editor.queryCommandValue(uiName);
if(!value){
combox.setValue(uiName);
return;
}
//ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
value && (value = value.replace(/['"]/g, '').split(',')[0]);
combox.setValue(value);
}
}
});
return combox;
},2/*index 指定添加到工具栏上的那个位置,默认时追加到最后,editorId 指定这个UI是那个编辑器实例上的,默认是页面上所有的编辑器都会添加这个按钮*/);
效果