澳门新浦京8455comckeditor插件开发简单实例

CKeditor就是FCKeditor,在发布一个新版本的时候,把自己的名字都改了,不要”F”。

昨天因为一个需求我们需要自定义ckeditor编辑器工具栏并放入一个插件,下面我来给大家介绍我的记录笔记,有需要可学习学习。

ckeditor添加自定义按钮整合swfupload实现批量上传图片
给ckeditor添加自定义按钮,由于ckeditor只能上传一张图片,如果要上传多张图片就要结合ckfinder,而ckfinder是收费的,所以就想通过自定义按钮整合swfupload实现一次上传多张图片的功能
首先下载并安装ckeditor。
下载swfupload解压拷贝到对应的文件目录下
3、自定义工具栏按钮:
澳门新浦京8455com,我们可以自定义ckeditor工具栏要显示的按钮,工具栏按钮定义可以参考这里。
现在我们需要向工具栏添加一个自定义功能的按钮。ckeditor工具栏中的每个按钮都是作为插件定义在ckeditorplugins
目录中。我们在ckeditorplugins中创建一个新文件夹imagedef。在imagedef文件夹内,我们创建一个plugin.js文件,它的代码如下:
CKEDITOR.plugins.add(
    “imagedef”, {
        requires: [“dialog”], //当按钮触发时弹出对话框
        init: function (a) {
            a.addCommand(“imagedef”, new
CKEDITOR.dialogCommand(“imagedef”));
            a.ui.addButton(
                “Imagedef”, {
                    label: “图片”,
                    command: “imagedef”,
                    icon: this.path + “imagedef.gif”
                });
            CKEDITOR.dialog.add(“imagedef”, this.path +
“dialogs/imagedef.js”);
        }
    }
);
在上面的代码中我们指定自定义按钮的图标imagedef.gif,imagedef.gif放在imagedef文件夹中。
在imagedef文件夹下新建一个dialogs目录,在dialogs目录下新建一个imagedef.js文件,就是上面代码调用的imagedef.js文件
CKEDITOR.dialog.add(
    “imagedef”,
    function (b)
    {
        return {
            title: “图片”,
            minWidth: 590,
            minHeight: 300,
            contents: [{
                id: “tab1”,
                label: “”,
                title: “”,
                expand: true,
                padding: 0,
                elements: [{
                    type: “html”,
                    html: initImageDlgInnerHtml()
//对话框中要显示的内容,这里的代码将发在下面
                }]
            }],
            onOk: function () { //对话框点击确定的时候调用该函数
                    var D = this;
                    var imes = getCkUploadImages();
//获取上传的图片,用于取路径,将图片显示在富文本编辑框中
                    $(imes).each(function () {
                        D.imageElement =
b.document.createElement(‘img’);
                        D.imageElement.setAttribute(‘alt’, ”);
                        D.imageElement.setAttribute(‘_cke_saved_src’,
$(this).attr(“src”));
                        D.imageElement.setAttribute(‘src’,
$(this).attr(“src”));
                        D.commitContent(1, D.imageElement);
                        if (!D.imageElement.getAttribute(‘style’)) {
                            D.imageElement.removeAttribute(‘style’);
                        }
                        b.insertElement(D.imageElement);
                    });
                },
                onLoad: function () { //对话框初始化时调用
                    initEventImageUpload();
//用于注册上传swfupload组件
                },
                onShow: function () {
                    clearCkImageUpload();
//在对话框显示时作一些特殊处理
                }
        };
    }
);
 
接下来我们需要注册imagedef插件。原文中的给出方法是在ckeditor.js中注册,这会使以后升级新版本遇到困难。提倡使用下面的方法在config.js中注册自定义插件:
CKEDITOR.editorConfig = function (config) {
    config.toolbar_Full = [
        [‘Source’, ‘Preview’, ‘-‘, ‘Templates’],

需求:我需要在编辑文本的时候,选择一段文字,点击自定义的按钮,就能够在这段文字后面增加一个图标,图标超链接去一个地址,以选中的文字作为参数。

1、首先下载并安装ckeditor。

        [‘Cut’, ‘Copy’, ‘Paste’, ‘PasteText’, ‘PasteFromWord’, ‘-‘,
‘Print’, ‘SpellChecker’, ‘Scayt’],
        [‘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’,
‘Blockquote’],
        [‘JustifyLeft’, ‘JustifyCenter’, ‘JustifyRight’,
‘JustifyBlock’],
        [‘Link’, ‘Unlink’, ‘Anchor’],
        [‘Imagedef’, ‘Table’, ‘HorizontalRule’, ‘Smiley’,
‘SpecialChar’, ‘PageBreak’],
        ‘/’,
        [‘Styles’, ‘Format’, ‘Font’, ‘FontSize’],
        [‘TextColor’, ‘BGColor’]
    ];
    config.resize_maxWidth = 775;
    config.removePlugins = ‘elementspath’; //去掉文本框下面出现body p

    config.extraPlugins = “imagedef”; //注册自定义按钮
};
 

做法:

2、自定义工具栏按钮:

最后,在ckeditor中显示自定义按钮linkbutton,代码如下:
下面代码是在页面上写的,当然可以根据自己的需求来定,写在什么位置
 

1、在CKeditor的plugins文件夹下,创建新文件夹”addmap”,这个名字可以自定义,这个名字是我项目中用的名字

我们可以自定义ckeditor工具栏要显示的按钮,工具栏按钮定义可以参考这里。

//编辑框初始化上传图片的回调———-自定义按钮插件
//上面有个cke_dialog_start_button_z样式是根据自己的需要来写的
function initEventImageUpload() { //对上传控件的注册
    ckeditorInitSwfu(“ck_fs_upload_progress”, “stop_id”,
“ck_btn_id”);
    $(“#ck_fs_upload_progress”).parent().find(“object”).css({
        “height”: “24px”,
        “width”: “82px”
    });
    $(“#ck_btn_start”).mouseover(function () {
        $(this).css({
            “cursor”: “hand”,
            “background-position”: “0 -1179px”
        });
    });
}

2、在addmap文件夹下,放一张gif图片”map.gif”,用来作图标用的。

现在我们需要向工具栏添加一个自定义功能的按钮。ckeditor工具栏中的每个按钮都是作为插件定义在ckeditorplugins
目录中。我们在ckeditorplugins中创建一个新文件夹linkbutton。在linkbutton文件夹内,我们创建一个plugin.js文件,它的代码如下:

function clearCkImageUpload() { //对对话框弹出时作特殊处理
    if ($(“#ck_fs_upload_progress”).html().indexOf(“.jpg”) != -1)
{
        $(“#ck_fs_upload_progress”).html(“”);
    }
    $(“#ck_pic_div”).html(“”);
}

3、在addmap文件夹下,新建”plugin.js”,编辑这个js文件,我们这里的代码是:

 代码如下

function getCkUploadImages() {
    return $(“#ck_pic_div”).find(“img”);
}
var ckSwfu; //初始化上传控件
function ckeditorInitSwfu(progress, btn, spanButtonPlaceHolder) {
    var uploadUrl =
“${BasePath}/commodity_com/img/uploadCommodityImg.ihtml?type=1”;
   
//在firefox、chrome下,上传不能保留登录信息,所以必须加上jsessionid。
    var jsessionid = $.cookie(“JSESSIONID”);
    if (jsessionid) {
        uploadUrl += “?jsessionid=” + jsessionid;
    }
    ckSwfu = new SWFUpload({
        upload_url: uploadUrl,
        flash_url:
“${BasePath}/res/base/plugin/swfupload/swfupload.swf”,
        file_size_limit: “4 MB”,
        file_types: “*.jpg;*.png;*.gif;*.jpeg;*.bmp”,
        file_types_description: “Web Image Files”,
        file_queue_limit: 0,
        custom_settings: {
            progressTarget: progress,
            cancelButtonId: btn
        },
        debug: false,
        button_image_url:
“${BasePath}/res/base/plugin/swfupload/button_notext.png”,
        button_placeholder_id: spanButtonPlaceHolder,
        button_text: “<span
class=’btnText’>上传图片</span>”,
        button_width: 81,
        button_height: 24,
        button_text_top_padding: 2,
        button_text_left_padding: 20,
        button_text_style: ‘.btnText{color:#666666;}’,
        button_cursor: SWFUpload.CURSOR.HAND,
        file_queued_handler: fileQueuedCk,
        file_queue_error_handler: fileQueueError,
        file_dialog_complete_handler: fileDialogCompleteCk,
        upload_start_handler: uploadStart,
        upload_progress_handler: uploadProgress,
        upload_error_handler: uploadError,
        upload_success_handler: uploadSuccessCk,
        upload_complete_handler: uploadComplete,
        queue_complete_handler: queueComplete
    });
};

复制代码 代码如下:(function() { //Section
1 : 按下自定义按钮时执行的代码 var a = { exec: function(editor) { var
data=””; var mySelection = editor.getSelection(); if (CKEDITOR.env.ie) {
mySelection.unlock(true); data =
mySelection.getNative().createRange().text; } else { data =
mySelection.getNative(); } if(data!=null&&data!=”){
editor.insertHtml(data+’a href=”/map_index.html?ad=’+data+'”img
border=”0″ height=”24″ src=”/images/map_icon.gif” width=”24″ //a’); } }
}, b = ‘addmap’; CKEDITOR.plugins.add(b, { init: function(editor) {
editor.addCommand(b, a); editor.ui.addButton(‘addmap’, { label: ‘add map
link’, icon: this.path + ‘map.gif’, command: b }); } });})();

复制代码

//开始上传图片
function ckUploadImageStart(obj) {
    ckSwfu.startUpload();
}

4、回到CKeditor的根目录,编辑config.js

(function(){
    //Section 1 : 按下自定义按钮时执行的代码
    var a= {
        exec:function(editor){
            alert(“这是自定义按钮”);
        }
    },
    //Section 2 : 创建自定义按钮、绑定方法
    b=’linkbutton’;
    CKEDITOR.plugins.add(b,{
        init:function(editor){
            editor.addCommand(b,a);
            editor.ui.addButton(‘linkbutton’,{
                label:’Link Button’,
                icon: this.path + ‘logo_ckeditor.png’,
                command:b
            });
        }
    });
})();

//回调重写
function fileQueuedCk(file) {
    try {
        if ($(“#ck_fs_upload_progress”).html().indexOf(“.jpg”) ==
-1) {
            $(“#ck_fs_upload_progress”).html(“”);
        }
        var progress = new FileProgress(file,
this.customSettings.progressTarget);
        progress.setStatus(“Pending…”);
        progress.toggleCancel(true, this);
        $(progress.fileProgressWrapper).css(“display”, “none”);
        $(“#ck_fs_upload_progress”).append(” ” + file.name);

复制代码 代码如下:CKEDITOR.editorConfig =
function( config ){// Define changes to default configuration here. For
example:config.language = ‘zh-cn’;//config.uiColor =
‘#AADC6E’;//字体.config.font_names =
‘宋体;楷体_GB2312;新宋体;黑体;隶书;幼圆;微软雅黑;Arial;Comic Sans
MS;Courier New;Tahoma;Times New Roman;Verdana;’;//工具按钮
config.toolbar=[ [‘Source’,’-‘,’Preview’],
[‘Cut’,’Copy’,’Paste’,’PasteText’,’PasteFromWord’,’-‘,’Print’,’Link’,’Unlink’,’Anchor’],
[‘Undo’,’Redo’,’-‘,’Find’,’Replace’,’-‘,’SelectAll’,’RemoveFormat’],
[‘addmap’]];

在上面的代码中我们指定自定义按钮的图标logo_ckeditor.png,logo_ckeditor.png放在linkbutton文件夹中。
接下来我们需要注册linkbutton插件

    } catch (ex) {
        this.debug(ex);
    }
}

config.extraPlugins = ‘addmap’;

-adding-a-new-toolbar-button/原文中的给出方法是在ckeditor.js中注册,这会使以后升级新版本遇到困难。提倡使用下面的方法在config.js中注册自定义插件:

//回调重写,上传成功后
function uploadSuccessCk(file, serverData) {
    try {
        var progress = new FileProgress(file,
swfu.customSettings.progressTarget);
        //progress.setComplete();
        //progress.setStatus(“上传成功!”);
        //progress.toggleCancel(false);
        $(progress.fileProgressWrapper).css(“display”, “none”);
        var json = eval(“(” + serverData + “)”);
        var img = ‘<div style=”float:left;”><img picUrl=”‘ +
json.url + ‘” src=”${BasePath!’
        ‘}/’ + json.url + ‘” style=”width:80px;height:80px”/><a
href=”javascript:void(0)”
onclick=”deletePic(this)”>X</a></div>’;

5、测试

 代码如下

        $(“#ck_pic_div”).append(img);
        $(“#ck_pic_div”).dragsort(“destroy”);
//图片排序,这里要下载dragsort插件
        $(“#ck_pic_div”).dragsort({
            dragSelector: “div”,
            dragBetween: true,
            placeHolderTemplate: “<div class=’placeHolder’
style=’float:left’><img /><a></a></div>”
        });
    } catch (ex) {}
}

复制代码

//回调重写,主要是设置参数,如果需要的参数没有,就清空上传的文件,为了解决下次选择会上传没有参数时的图片
function fileDialogCompleteCk(numFilesSelected, numFilesQueued) {
    try {

CKEDITOR.editorConfig = function( config )
{
    // Define changes to default configuration here. For example:
    // config.language = ‘fr’;
    // config.skin = ‘office2003’;
    config.extraPlugins=”linkbutton”
};

        var commoNo = $(“#commoNo”).val();
        var brandNo = $(“#brand option:selected”).val();
        var catNo = $(“#thirdCommon option:selected”).val();
        //初始化上传图片
        if (brandNo != “” && commoNo != “” && catNo != “”) {
            this.addPostParam(“commoNo”, commoNo);
            this.addPostParam(“thirdCatNo”, catNo);
            this.addPostParam(“brandNo”, brandNo);
            if (numFilesSelected > 0) {
               
document.getElementById(this.customSettings.cancelButtonId).disabled =
false;
            }
        } else {
            for (var i = 0; i < numFilesSelected; i++) {
                var promitId = this.customSettings.progressTarget;
                $(“#” + promitId).find(“*”).remove();
                var fileId = this.getFile().id;
                this.cancelUpload(fileId, false);
            }
            $(“#ck_fs_upload_progress”).html(“”);
            alert(“请选择分类和品牌!”);
        }
    } catch (ex) {
        this.debug(ex);
    }
}

最后,在ckeditor中显示自定义按钮linkbutton,代码如下:

 代码如下

复制代码

<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=gb2312″
/>
<title>自定义按钮</title>
<script type=”text/javascript” src=”ckeditor.js”></script>
<style type=”text/css”>
body{font-size:12px;line-height:1.8;font-family:’微软雅黑’;}
</style>
</head>
 
<body>
<textarea id=”ckeditor”></textarea>
<script type=”text/javascript”>
    CKEDITOR.replace( ‘ckeditor’,{
        toolbar :
            [
                [ ‘Bold’, ‘Italic’, ‘-‘, ‘NumberedList’,
‘BulletedList’, ‘-‘, ‘Link’, ‘Unlink’,’-‘,’linkbutton’ ]
            ],
        extraPlugins:”linkbutton”   
//注册linkbutton,也可在config.js中注册
    });
</script>
</body>
</html>

注意:自定义插件的名称必须在任何地方都要保持一致。

写一个demo.html文件进行测试

     
我们在${ckeditor}根目录下建立一个demo.html文件来测试下我们刚写的插件是否有效,内容如下:

 代码如下

复制代码

<html><head> <title>CKEditor插件编写示例-Powered By
mzone.cc</title> <meta http-equiv=”Content-Type”
content=”text/html; charset=utf-8″/> <script
type=”text/javascript”
src=”ckeditor.js”></script></head><body> <textarea
cols=”80″ id=”editor1″ name=”editor1″ rows=”10″>This is the
content!</textarea> <script>  CKEDITOR.replace(“editor1”,
{   toolbar : ‘MyBasic’,   height : 300,   width :
800  }); </script></body></html>     

然后在浏览器中打开demo.html文件,就可以看到在编辑器的工具栏中最后一个就是我们刚写的插件了,如下图所示:

 

澳门新浦京8455com 1

1、首先下…

You can leave a response, or trackback from your own site.

Leave a Reply

网站地图xml地图