最近由于项目需要在富文本中,添加专题模块(固定样式)插入到富文本的某个地方。根据思路,分为以下几步。
第一步:样式及JS修改
在ueditor.css中添加按钮样式
在ueditor.config.js设置按钮KEY
重要的一步,在ueditor.all.js 中添加按钮,搜索 btnCmds,不然不会显示到工具栏上。
基础配置完成,接下来就是完成按钮功能,我的功能是弹出一个层,选择好数据之后,把整个层的HTML插入到焦点位置
第二步,按钮功能
直接在ueditor.all.js 末尾添加如下JS:
/**
* 插入专题
* @command craftsmanspecial
* @method execCommand
* @param { String } cmd 命令字符串
* @example
* ```javascript
* editor.execCommand('craftsmanspecial');
* ```
*/
UE.commands['craftsmanspecial'] = {
execCommand : function() {
var me = this;
try {
if(typeof SpecialLookup === "function") {
SpecialLookup(me.key);//回传富文本所在的元素ID
} else {
console.log("SpecialLookup is not full");
}
} catch(e) {
console.log("SpecialLookup:"+e);
}
},
queryCommandState : function() {
return false;
}
};
在使用富文本的页面,加入layui弹框方法
window.SpecialLookup = function(div_id){
layui.use(['form', 'upload'],function(){
layer.open({
type:2,
content: 'select_special_lookup.html?hd_id=hd_special_'+div_id+'&jq_fn=selectSpecialLookup&hd_css='+div_id,
title:'插入专题',
area: ['900px', '700px'],
cancel: function(){
}
});
});
}
在弹框里面,查找、组合所需数据,通过回调方法,回传到父页面的方法
window.selectSpecialLookup = function(hd_id,hd_css,special_type,special_html,special_json){
var special_html_div = "<div data-type='"+special_type+"' data-json='"+special_json+"' class='special_ueditor_css_craftsman'>专题效果,需预览查看!</div>";
if(hd_id.indexOf('edit_')>-1){
edit_ue.execCommand('inserthtml',special_html_div,true);
}else{
add_ue.execCommand('inserthtml',special_html_div,true);
}
}
注:inserthtml命令,第三个参数传true,表示原样插入html代码,否则会【官方:
- 警告: 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
】
最终的效果如下:
PS:欢迎留言交流学习!