天天看点

关于CKEditor4.5.6的使用,自定义toolbar配置,上传图片案例(SpringMVC+MyBatis案例),自定义行高,去编辑器的中内容,将编辑器中内容设置到指定的位置等



关于ckeditor的一个配置整理,改文件为config.js:

关于CKEditor4.5.6的使用,自定义toolbar配置,上传图片案例(SpringMVC+MyBatis案例),自定义行高,去编辑器的中内容,将编辑器中内容设置到指定的位置等

文件内容如下:

/**

 * @license copyright (c) 2003-2016, cksource - frederico knabben. all rights reserved.

 */

ckeditor.editorconfig = function( config ) {

 // define changes to default configuration here. for example:

 // config.language = 'fr';

 // config.uicolor = '#aadc6e';

 config.toolbargroups = [

  { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },

  { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },

  { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },

  { name: 'forms', groups: [ 'forms' ] },

  { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },

  '/',

  { name: 'links', groups: [ 'links' ] },

  { name: 'insert', groups: [ 'insert' ] },

  { name: 'colors', groups: [ 'colors' ] },

  { name: 'styles', groups: [ 'styles' ] },

  { name: 'tools', groups: [ 'tools' ] },

  { name: 'paragraph', groups: [ 'list', 'blocks', 'bidi', 'align', 'indent', 'paragraph' ] },

  { name: 'others', groups: [ 'others' ] },

  { name: 'about', groups: [ 'about' ] }

 ];

 // config.removebuttons = 'source,save,templates,cut,undo,find,scayt,selectall,paste,copy,redo,newpage,preview,print,form,bold,removeformat,link,image,textcolor,outdent,justifyleft,bidiltr,blockquote,numberedlist,uicolor,lineheight';

 config.line_height ='8px;9px;10px;11px;12px;13px;14px;15px;16px;17px;18px;19px;20px;21px;22px;23px;24px;25px;26px;27px;28px;29px;30px;31px;32px;33px;34px;35px;36px;37px;38px;39px;40px;41px;42px;43px;44px;45px;46px;47px;48px;49px;50px;51px;52px;53px;54px;55px;56px;57px;58px;59px;60px;61px;62px;63px;64px;65px;66px;67px;68px;69px;70px;71px;72px;';

 config.skin = 'office2013';

 config.extraplugins='imagepaste';

 config.pastefromwordremovefontstyles = false;

 config.pastefromwordremovestyles = false;

 config.extraplugins = 'uploadwidget';

 config.extraplugins = 'notificationaggregator';

 config.extraplugins = 'notification';

 config.extraplugins = 'uploadimage';

 config.extraplugins = 'toolbar';

 config.extraplugins = 'button';

 config.extraplugins = 'filetools';

 config.extraplugins = 'clipboard';

 config.extraplugins = 'dialog';

 config.extraplugins = 'dialogui';

 config.extraplugins = 'widget';

 config.extraplugins = 'lineutils';

 config.secureimageuploads = true;

 config.image_previewtext=' '; //预览区域显示内容

 //config.filebrowseruploadurl: "import/ckeditoruploadfile.action";

 config.filebrowserimageuploadurl = basepath + "/import/ckeditoruploadfile.action?type=image"; //待会要上传的action或servlet

};

关于图片上传部分可以参考:

<a target="_blank" href="http://blog.csdn.net/itmyhome1990/article/details/17264627">http://blog.csdn.net/itmyhome1990/article/details/17264627</a>

实现过程中的一个案例

/*

 * name       :tuzuoquan

 * mail       :[email protected]

 * date       :2016/01/13

 * version    :1.0

 * description:xxxxxx对应的js

 * copyright (c) 2015-12-31

if (ckeditor.env.ie &amp;&amp; ckeditor.env.version &lt; 9)

   ckeditor.tools.enablehtml5elements(document);

 * 编辑器对应的操作方法

 *

 * 关于在线编辑器的文档:http://sdk.ckeditor.com/samples/resize.html

var ckeditorhandler = (function($) {

   return {

      /**

       * 初始化参数配置

       */

      ckeditorconfig:function(){

          //去掉开始进来的时候自动添加 br

          ckeditor.config.entermode = ckeditor.enter_br;

          //去掉开始进来的时候自动添加p

          ckeditor.config.shiftentermode = ckeditor.enter_p;

          ckeditor.config.font_names='微软雅黑;宋体;新宋体;黑体;隶书;幼圆;楷体_gb2312;仿宋_gb2312;方正舒体;方正姚体;华文隶书;华文新魏;华文行楷;sans-serif;arial;comic sans ms;courier new;tahoma;times new roman;verdana;'

          ckeditor.config.line_height="1em;1.1em;1.2em;1.3em;1.4em;1.5em";

       },

       * 初始化工具条的相关信息

      inittoolbar:function(){

         ckeditor.config.toolbar = 'full';

         /**

          * 其中("-")为空间栏的水平分割,("/")为换行

          *

          * 以下:full表示的所有的操作

          */

         ckeditor.config.toolbar_full =

         [

            { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },

            { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },

            { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },

            { name: 'forms', groups: [ 'forms' ] },

            { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },

            '/',

            { name: 'links', groups: [ 'links' ] },

            { name: 'insert', groups: [ 'insert' ] },

            { name: 'colors', groups: [ 'colors' ] },

            { name: 'styles', groups: [ 'styles' ] },

            { name: 'tools', groups: [ 'tools' ] },

            { name: 'paragraph', groups: [ 'list', 'blocks', 'bidi', 'align', 'indent', 'paragraph' ] },

            { name: 'others', groups: [ 'others' ] },

            { name: 'about', groups: [ 'about' ] }

         ];

         ckeditor.config.toolbar_basic =

             ['source','preview'],

             ['cut','copy','paste','pastetext','pastefromword','-','spellchecker'],

             ['undo','redo','-','find','replace','-','selectall','removeformat'],

             ['form', 'checkbox', 'radio', 'textfield', 'textarea', 'select', 'button', 'imagebutton', 'hiddenfield'],

             ['bold','italic','underline','strike','-','subscript','superscript'],

             ['numberedlist','bulletedlist','-','outdent','indent'],

             ['justifyleft','justifycenter','justifyright','justifyblock'],

             ['link','unlink','anchor'],

             ['image','flash','table','specialchar'],

             ['styles','format','font','fontsize'],

             ['textcolor','bgcolor'],

             ['lineheight']

       * 在线编辑器的初始化过程

       * textcontent   :表示的是文本组件的内容

      init:function(textcontent){

          //注意:这里的tpl-content-editor是编辑器对应的id值

          if(ckeditor.instances.tplcontenteditor) {

             var editor = ckeditor.instances["tplcontenteditor"];

             //console.log("1------------------------------------------");

             //console.log(editor.getdata());

             //editor.setdata(editor.setdata(textcontent));

             //console.log("2------------------------------------------");

             //销毁编辑器,然后新增一个

             if(editor) editor.destroy(true);

          }

          ckeditorhandler.ckeditorconfig();

          //初始化工具栏

          ckeditorhandler.inittoolbar();

          ckeditor.replace("tplcontenteditor",

          {

             toolbar:'basic',

             height:'300',

             width:'auto'

          });

          //为编辑器设置内容

          ckeditor.instances.tplcontenteditor.setdata(textcontent);

       /**

       * 2、判断一个字符串变量是否为空

       * 如果不为空:返回true

       * 如果为空:返回false

      isnotblank:function(variable){

         return (variable != null &amp;&amp; typeof(variable) != "undefined" &amp;&amp; variable != undefined &amp;&amp; variable != "") ? true : false;

      },

        * 通过编辑的icon获得组件元素,查找父元素,直到找到含有classname这个类选择器的元素停止

        * domele         :表示的是编辑的元素

        */

       /**

         * 将str1这个原始的字符串中的str2全部换成str3

         * str1      :最原始的字符串

         * str2      :要被替换的字符串

         * str3      :最终替换成的字符串

         *

         * 此外可以增加string对象的原型方法:

         * string.prototype.replaceall = function(str2,str3){

       *     return this.replace(new regexp(str2,"gm"),str3);

       * }

         */

        replaceall:function(str1,str2,str3) {

            var newstr  = str1;

            if(this.isnotblank(str1)) {

                //其中gm中的g表示"执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)"

                //其中gm中的m表示执行多行匹配

                newstr = str1.replace(new regexp(str2,"gm"),str3);

            }

            return newstr;

        },

        /**

         * 清除样式

        removecss:function(id,childpathofselectedelement,csstype){

            //替换原来的css样式

            var oldstylecss = $("#generatedcss").html().replace(

                new regexp("#"+ id + childpathofselectedelement + ".*?{.*"+csstype+".*?}"),"");

            oldstylecss = this.replaceall(oldstylecss,"\r\n","");

            $("#generatedcss").text(oldstylecss);

       obtaincomponentele:function(domele,classname) {

          var tempobj = domele;

          while(!$(tempobj).parent().hasclass(classname)) {

             tempobj = $(tempobj).parent().get(0);

          return $(tempobj).parent().get(0);

        * 存储的是要编辑的对象

       editobj : null,

        * 表示的是否是多列的

       ismultiseriate : false,

        * 1、点击编辑按钮的时候执行的操作

        * domele                     :代表的是编辑按钮

        * selectedelementinfo        :表示的是被选中的元素

        * childpathofselectedelement :表示的是放置内容的位置

        *

        * ismultiseriate             :表示的是是否多列

        * obj                        :表示的是被点击的个元素

        * 如果是单列的:

        * 比如点击"text"组件"编辑"按钮的时候传递进入的参数是:(this,selectedelementinfo,'',false,'')

        * 如果实在配置文件中点击弹出的,传递的参数是:('',selectedelementinfo,' .xxx .xxx',false,''),其中' .xxx .xxx'是你要改变的元素

        * 如果是多列的:

        * ('',selectedelementinfo,'',true,editobj)

       tpleditselectedcontent:function(domele,selectedelementinfo,childpathofselectedelement,ismultiseriate,editobj) {

          //存储的是点击的对象

          ckeditorhandler.editobj = editobj;

          //存储是否是多列的情况

          ckeditorhandler.ismultiseriate = ismultiseriate;

          //如果是多列的

          if(ckeditorhandler.ismultiseriate) {

             //获得要编辑的元素的内容:

             var textcontent = $(ckeditorhandler.editobj).html();

          } else {

             //获得domele这个编辑按钮的组件

             var componentele = null;

             if(ckeditorhandler.isnotblank(domele)) {

                componentele = ckeditorhandler.obtaincomponentele(domele,"tpl-monitored-class");

             } else {

                var id = selectedelementinfo.get("id");

                componentele = $("#" + id);

             }

             //将当前元素的id存储到隐藏域中

             $(".tpl-edit-popup-window #componentid").val($(componentele).attr("id"));

             //存储要设置的元素的值

             if(!ckeditorhandler.isnotblank($.trim(childpathofselectedelement))) {

                childpathofselectedelement = " .tpl-component-2015-12-30-text-content";

             //将要编辑的后代的值存到隐藏域中

             $(".tpl-edit-popup-window #childpathofselectedelement").val(childpathofselectedelement);

             //获得当前要编辑的元素的id

             var componentid = $(componentele).attr("id");

             var textcontent = $("#" + componentid + " " + childpathofselectedelement).html();

          //获得文本组件中的内容

           ckeditorhandler.init(textcontent);

            $('.theme-popover-mask').fadein(10);

           $('.theme-popover').slidedown(20);

        * 点击取消的时候执行的动作

        * @return

       tpleditcancel:function() {

          $('.theme-popover-mask').fadeout(100);

          $('.theme-popover').slideup(200);

        * 点击"确定的时候执行的动作"

       tpleditok:function() {

          //获得编辑器中的内容

          var editorcontent = ckeditor.instances.tplcontenteditor.getdata();

          var id = selectedelementinfo.get("id");

          /**

           * 判断是否是多列的

           */

             $(ckeditorhandler.editobj).empty();

             $(ckeditorhandler.editobj).append(editorcontent);

             //1、首先判断编辑器内容中第一个子标签的内容是否是&lt;pre&gt;,若是,则在后面不在添加&lt;pre&gt;

             //$("&lt;div&gt;&lt;/div&gt;").append(editorcontent).first().prop("tagname");

             //$("&lt;div&gt;&lt;/div&gt;").append(editorcontent).first().prop("nodename");

             //获得要修改的组件的id

             var componentid = $(".tpl-edit-popup-window #componentid").val();

             //获得组件中要放置内容的元素

             var childpathofselectedelement = $(".tpl-edit-popup-window #childpathofselectedelement").val();

             $("#" + componentid + " " + childpathofselectedelement).empty();

             $("#" + componentid + " " + childpathofselectedelement).append(editorcontent);  

          if($("#" + id + " .picturegroup #topmarquee_1 li").length&gt;0){

             var currcount = $("#" + id + " .picturegroup #topmarquee_1 li").length;

               var baseheight = 0;

            var i=0;

            for(;i&lt;currcount;i++){

                baseheight += $("#" + id + " .picturegroup #topmarquee_1 li").eq(i).outerheight(true);

               var dyheight = baseheight  + 'px';

               var divheight = baseheight  * 2  + 'px';      

               $("#" + id + " .picturegroup .picture-holder").css("height", dyheight);

               $("#" + id + " .picturegroup  div").css("height", divheight);

          /*if($("#" + id + " .picturegroup #erwm").length&gt;0){

             this.removecss(id," .picturegroup","height");

             this.removecss(id," .picturegroup #erwm","height");

             var height = parsefloat($("#picheight").val());

             var spanheight = $("#" + id + " .picturegroup #erwm .bottomcontent").height();

             console.log(spanheight);

             $("#" + id + " .picturegroup").css("height","'+(height+spanheight)+'+'px'");

             $("#" + id + " .picturegroup #erwm").css("height","'+(height+spanheight)+'+'px'");

          }*/

          //恢复默认值

          ckeditorhandler.ismultiseriate = false;

          ckeditorhandler.editobj = null;

       }

   }

})(jquery);

 * 1、页面加载完成后执行的动作

$(function(){

   $('.theme-poptit .close').click(function(){

      $('.theme-popover-mask').fadeout(100);

      $('.theme-popover').slideup(200);

   });

});

关于图片上传的后台操作,使用的框架是spring+springmvc+mybatis

package xxx.controller.upload;

import org.apache.log4j.logger;

@controller

@requestmapping(value = "/import", method = { requestmethod.get,requestmethod.post })

public class importcontroller extends basecontroller{

         /** 用于打印日志 */

         private static final logger logger = logger

                            .getlogger(specialcontroller.class);

          * 此方法用于ckeditor的本地上传图片的功能

          * @param param

          * @param imagefile

          * @return

         @requestmapping(value = "/ckeditoruploadfile", produces = "text/json")

         public void ckeditoruploadfile(

                            @requestparam("upload") multipartfile upload,

                            httpservletrequest request,

                            httpservletresponse response,

                            @requestparam("ckeditorfuncnum")string ckeditorfuncnum)

                            throws illegalstateexception,ioexception {

                   printwriter out = response.getwriter();

                   response.setcharacterencoding("utf-8");

                   //判断扩展文件名是否正确

                   string uploadcontenttype = upload.getcontenttype();

                   if(uploadcontenttype.equals("image/pjpeg") || uploadcontenttype.equals("image/jpeg")) {

                   } else if(uploadcontenttype.equals("image/png") || uploadcontenttype.equals("image/x-png")) {

                   } else if(uploadcontenttype.equals("image/gif")) {

                   } else if(uploadcontenttype.equals("image/bmp")) {

                   } else {

                            out.println("&lt;script type=\"text/javascript\"&gt;");

                            out.println("window.parent.ckeditor.tools.callfunction(" + ckeditorfuncnum + ",''," + "'文件格式不正确(必须为.jpg/.gif/.bmp/.png文件)');");

                            out.println("&lt;/script&gt;");

                            return;

                   }

                   if (!upload.isempty()) {

                            try {

                                     //如果上传的图片大于10m,返回提示

                                     if (upload.getsize() &gt; 10 * 1024 * 1024) {

                                               out.println("&lt;script type=\"text/javascript\"&gt;");

                                               out.println("window.parent.ckeditor.tools.callfunction(" + ckeditorfuncnum + ",''," + "'文件大小不得大于600k');");

                                               out.println("&lt;/script&gt;");

                                               return;

                                     }

                                     calendar calendar = calendar.getinstance();//获取当前时间

                                     //时间路径,解压文件,以年月日创建文件夹

                                     string datapath ="/"+calendar.get(calendar.year)+"/"

                                                                 + (calendar.get(calendar.month)+1)+"/" + calendar.get(calendar.date)+"/";

                                     // 原文件名

                                     string srcname = upload.getoriginalfilename();

                                     //获取上传文件后缀

                                     string suffix = srcname.substring(srcname.lastindexof(".") + 1,

                                                        srcname.length()).tolowercase();

                                     //随机生成32位id,用于解压文件目录

                                     string uuid = uuidgenerator.generate();

                                     //新的文件名,随机的uuid;

                                     string picname = uuid +"."+suffix;

                                     //图片存储的实际路径

                                     string urlprefix = extendedserverconfig.getinstance().getstringproperty("visite_prefix_url");

                                     //大图缩略图生成路径

                                     string thumbnailpath =extendedserverconfig.getinstance()

                                                                 .getstringproperty("thumbnail_path")+ extendedserverconfig.getinstance()

                                                                 .getstringproperty("save_big_thumbnail")+datapath;

                                     //生成缩略图保存数据库路径

                                     string savepath =extendedserverconfig.getinstance()

                                                        .getstringproperty("save_big_thumbnail")+datapath+picname;

                                     //文件夹不存在,则创建

                                     file destfile = new file(thumbnailpath);

                                if(!destfile.exists()){

                                         destfile.mkdirs();

                                }

                                     // 写文件

                                     inputstream fi = upload.getinputstream();

                                     //上传文件写入到配置文件夹下

                                     fileutils.writefile(fi, thumbnailpath+picname);

                                     file file = new file(thumbnailpath+picname);

                                     if(file.exists()) {

                                               out.println("window.parent.ckeditor.tools.callfunction(" + ckeditorfuncnum + ",'" + urlprefix + savepath + "','')");

                            } catch (exception e) {

                                     e.printstacktrace();

                            }

                   return;

         }

}