前端 2017-04-14 22:35:06

前端富文本编辑器ueditor使用

项目引入ueditor

  • 下载官方ueditor jsp版本
    http://ueditor.baidu.com/website/download.html

  • 项目下创建ueditor目录放置ueditor资源如图

    图片描述

    由于ueditor.config.js该配置文件需要经常修改,为了方便打包,将文件单独放置到自己项目的js文件夹下。
    同时在js目录下创建ueditor.custom.js,该文件编写二次开发的代码。

requirejs引入ueditor

require.config({
    waitSeconds: 15,
    paths: {
        'jquery': 'lib/jquery-1.11.3',
        //ueditor
        'ueditor': '../ueditor/ueditor.all',
        'ueditor_cn': '../ueditor/lang/zh-cn/zh-cn',
        'ueditor_config': 'lib/ueditor.config',
        'editor_custom': 'lib/ueditor.custom',
        'zeroclipboard': '../ueditor/third-party/zeroclipboard/ZeroClipboard'
    },
    shim: {
        'ueditor': {
            deps: ['zeroclipboard', 'ueditor_config'],
            exports: 'UE',
            init: function (ZeroClipboard) {
                //导出到全局变量,供ueditor使用
                window.ZeroClipboard = ZeroClipboard;
            }
        },
        'ueditor_cn': ['ueditor'],
        'editor_custom': ['ueditor']
    }
});

require(['jquery','ueditor', 'editor_custom', 'ueditor_cn'], function ($,  UE) {
    
});

初始化ueditor

ueditor.config.js里

window.UEDITOR_HOME_URL 资源文件根路径
iframeCssUrl: URL + '../css/ueditor.iframe.css' 给编辑区域的iframe引入一个css文件

1.html: 在需要放置编辑器的地方加入

<script id="editor" type="text/plain"></script>

2.script:

/**
 * 初始化ueditor
 */
function initUeditor(onReady) {
    editor = UE.getEditor('editor', {});

    editor.addListener('contentChange', function () {
        console.log('选区发生改变');

    });

    editor.ready(function () {
        // ueditor 初始化完成,onReady为成功回调函数
        onReady && onReady();
    });

}

工具栏添加按钮

var uploadImageName = '上传图片';

UE.registerUI(uploadImageName,function(editor,uiName){
    //注册按钮执行时的command命令,使用命令默认就会带有回退操作
    editor.registerCommand(uiName,{
        execCommand:function(){
            $('#imageModal').modal('show');
        }
    });

    //创建一个button
    var btn = new UE.ui.Button({
        //按钮的名字
        name:uiName,
        //提示
        title:uiName,
        //需要添加的额外样式,指定icon图标,这里默认使用一个重复的icon
        cssRules :'background-position: -726px -77px;',
        //点击时执行的命令
        onclick:function () {
            //这里可以不用执行命令,做你自己的操作也可
           editor.execCommand(uiName);
        }
    });

    //当点到编辑内容上时,按钮要做的状态反射
    editor.addListener('selectionchange', function () {
        var state = editor.queryCommandState(uiName);
        if (state == -1) {
            btn.setDisabled(true);
            btn.setChecked(false);
        } else {
            btn.setDisabled(false);
            btn.setChecked(state);
        }
    });

    //因为你是添加button,所以需要返回这个button
    return btn;
} , 54/*index 指定添加到工具栏上的那个位置,默认时追加到最后,editorId 指定这个UI是那个编辑器实例上的,默认是页面上所有的编辑器都会添加这个按钮*/);

ueditor常用api

  1. 插入html代码
    editor.execCommand('insertHtml', h);

  2. 插入图片
    editor.execCommand('insertimage', {src: url });

  3. 获取内容
    editor.getContent();

  4. 获取内容长度
    editor.getContentLength(false)