UEditor动态设置工具栏

来源:互联网 发布:淘宝日用品代理 编辑:程序博客网 时间:2024/06/07 06:49

UEditor是百度开发的开源富文本编辑器,可以很方便的实现富含各种格式的文档的编辑。如果我们要在开发的web项目,比如java web项目中使用UEditor,需要如下代码:

UE.getEditor('editor'); 

这样就可以在jsp页面中,看到完整的UEditor的界面如下图所示。


我们可能会觉得工具栏的按钮太多了,有些在我们的项目中并不需要。于是,我们可以采用下面的方式进行工具栏的定制:

UE.getEditor('editor', {<span style="white-space:pre"></span>toolbars: [<span style="white-space:pre"></span>[<span style="white-space:pre"></span>        <span style="white-space:pre"></span>'undo', //撤销<span style="white-space:pre"></span>        <span style="white-space:pre"></span>'redo', //重做<span style="white-space:pre"></span>        <span style="white-space:pre"></span>'bold', //加粗<span style="white-space:pre"></span>        <span style="white-space:pre"></span>'indent', //首行缩进<span style="white-space:pre"></span>        <span style="white-space:pre"></span>'italic', //斜体<span style="white-space:pre"></span>        <span style="white-space:pre"></span>'fullscreen', //全屏<span style="white-space:pre"></span>    <span style="white-space:pre"></span>]<span style="white-space:pre"></span>]<span style="white-space:pre"></span>});

这样,我们就得到了下面定制了工具栏的编辑器:


上面这两种方式都是在初始化的时候,一次性地定制工具栏。(第一种没有指定特定的按钮,默认所有按钮都需要)。可是在项目中,我们可能会需要动态地改变工具栏中显示哪些按钮。比如我们可能先浏览一篇文章,这个时候并不需要太多的工具栏按钮,而设置一个编辑按钮,当点击了该按钮之后,才显示出需要的工具栏按钮。

我在项目中就遇到了这个需求。刚开始在网上一直搜索不到答案。于是,经过我对UEditor文档的专心研究。发现可以通过一种“曲线”的方式实现这个功能。

假设jsp页面中已经有一个id为editor的编辑器,它的工具栏是显示了所有的按钮。通过下面这个函数就可以实现将按钮缩减到5个:

UE.getEditor('editor').destroy();UE.getEditor('editor', {toolbars: [[        'undo', //撤销        'redo', //重做        'bold', //加粗        'indent', //首行缩进        'italic', //斜体        'fullscreen', //全屏    ]]});
原因就是调用了UEditor的API中的destroy()函数,它会将编辑器“销毁”掉,退回到textarea状态(这个编辑器其实就是通过textarea加上javascript代码来实现的。我们可以把上面的代码封装到一个函数中,只要运行这个函数(比如点击了一个按钮来触发该函数),就可以改变编辑器显示的按钮,实现了动态控制工具栏按钮的需求。

0 0
原创粉丝点击