百度ueditor 编辑器使用问题收集

百度ueditor 编辑器使用问题收集

1 setContent 有时不起作用

页面区显示编辑内容的控件如下
<textarea id="contents" name="contents" style="width: 100%; height: 300px"></textarea>
js中
在创建编辑器后,setContent 内容显示不出来,但偶尔有可以的时候,如下

var ue = UE.getEditor("contents"); // contents 为textarea 的id
ue.setContent(“待显示内容”);

改成如下方式即可
var ue = UE.getEditor("contents");
ue.addListener("ready", function() {
                        // editor准备好之后才可以使用
                        ue.setContent(“待显示内容”);

                    });

一般情况下上面的是没有问题,但偶尔还是会有内容赋值不上的情况索性再加了一个,如下:

ue.addListener("ready", function () {
                        // editor准备好之后才可以使用
                        ue.setContent(result.Contents);
                    });

                    ue.ready(function () {
                        // editor准备好之后才可以使用
                        ue.setContent(result.Contents);
                    });

这样后基本上没有问题了,至少目前还没发现

2 添加的html元素样式不起作用,div等元素被替换了

首先在ueditor.all.js文件内搜索allowDivTransToP,找到如下的代码,将true设置为false
me.setOpt('allowDivTransToP',false);
//默认的过滤处理
//进入编辑器的内容处理
然后再接着下边的addInputRule方法中将switch代码段中的case style,script都给注释或者删掉。
me.addInputRule(function (root) {


//删除switch下的case style 和script
switch (node.tagName) {
case 'a':
if (val = node.getAttr('href')) {
node.setAttr('_href', val)
}
break;
完成以上操作之后,保存即可。再次插入html时,样式就可以显示了。
解释一下以上操作的意义。
第一步将allowDivTransToP设置为false是因为默认的设置是将div自动转换为p,这样写好的样式就找不到相应的div
了,所以才渲染不上的。
第二步将addInputRule函数中的switch 代码段中的case style ,script选择给删除或者注释,是为了避免出现编辑器将style或script自动的转换成别的标签。
好了,大家可以试一试,看看效果。
 

3 隐藏部分不要的按钮

在ueditor.config.js文件中,找到 toolbars: [[
里面的内容就是各个工具了,比如:
, toolbars: [[
            'fullscreen', 'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
            'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
            'print', 'preview', 'searchreplace', 'help', 'drafts'
        ]]
直接去掉不想要显示的按钮的名字,
也可以用下面的方法,在页面引用编辑器实例化的时候,如下:
var ue = UE.getEditor('container', {
    toolbars: [
        ['fullscreen', 'source', 'undo', 'redo', 'bold']
    ],
    autoHeightEnabled: true,
    autoFloatEnabled: true
});
这样去实例化 然后toolbars里面的单词就是你要显示的按钮
toolbars所有按钮单词对应说明文档地址

http://fex.baidu.com/ueditor/#start-toolbar

4 UEditor编辑器如何关闭抓取远程图片本地化功能


解决办法:
1、打开ueditor.all.js
   搜索“抓取”的时候出现以下代码:
   
// plugins/catchremoteimage.js  
///import core  
///commands 远程图片抓取  
///commandsName  catchRemoteImage,catchremoteimageenable  
///commandsTitle  远程图片抓取  
/** 
 * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片 
 */  
UE.plugins['catchremoteimage'] = function () {  
    var me = this,  
        ajax = UE.ajax;  
    /* 设置默认值 */  
    if (me.options.catchRemoteImageEnable === false) return;  
    me.setOpt({  
        catchRemoteImageEnable: false  
    });  
    //.......  
};  
发现:catchRemoteImageEnable
2、打开ueditor.config.js
    在空白处添加
    
//抓取远程图片是否开启,默认true  
,catchRemoteImageEnable:false 

5 后端配置项没有正常加载,上传插件不能正常使用

如果出现上面的问题,你在浏览器中打开
http://你的域名/ueditor/net/controller.ashx
就可以看到出现的信息,根据信息去修改即可,当打开没有问题后,打开下面的地址
http://你的域名/ueditor/net/controller.ashx?action=config

能正常显示配置信息说明配置成功了

6 编辑时换行<p></p>问题

在编辑器里换行后,在代码查看发现每个换行的内容都被<p></p>修饰,其实想要的就是<br>,可通过在ueditor.all.js里

约6720行,找到如下这段:

    var Editor = UE.Editor = function (options) {
        var me = this;
        me.uid = uid++;
        EventBase.call(me);
        me.commands = {};
        me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
        //this is add by 20191029 enterTag
        me.options.enterTag = "br";

增加的这行 me.options.enterTag = "br"; 的意思是以<br>作为换行符

或者直接改默认配置:

UE.Editor.defaultOptions = function(editor){

    var _url = editor.options.UEDITOR_HOME_URL;
    return {
        isShow: true,
        initialContent: '',
        initialStyle:'',
        autoClearinitialContent: false,
        iframeCssUrl: _url + 'themes/iframe.css',
        textarea: 'editorValue',
        focus: false,
        focusInEnd: true,
        autoClearEmptyNode: true,
        fullscreen: false,
        readonly: false,
        zIndex: 999,
        imagePopup: true,
        enterTag: 'p',
        customDomain: false,
        lang: 'zh-cn',
        langPath: _url + 'lang/',
        theme: 'default',
        themePath: _url + 'themes/',
        allHtmlEnabled: false,
        scaleEnabled: false,
        tableNativeEditInFF: false,
        autoSyncData : true,
        fileNameFormat: '{time}{rand:6}'
    }
};

enterTag: 默认为p 改为br

7 图片上传问题

编辑器里涉及到图片上传,如果要改造成自己的图片处理程序,有些地方需要修改,以我自己的改造为例,列出需要修改的地方:

因为是单独的图片上传接口,要集成要这个编辑器

1 \ueditor\dialogs\image\image.js

前端因为是html页面,在登录成功后把得到的token先存

在image.js里存出,传到后续要用到的页面


uploader.on('uploadBeforeSend', function (file, data, header) {
                //这里可以通过data对象添加POST参数
                data.sid = GetApiTokenCache();        //add 
                //console.log("data.sid=" + data.sid);
                header['X_Requested_With'] = 'XMLHttpRequest';
            });

var dataStorage = window.localStorage;

    //从本地存储取用户token
    function GetApiTokenCache() {
        var sessionId = dataStorage.getItem("ApiUserToken");
        if (!sessionId || sessionId.length < 1) {
            sessionId = "";
        }
        return sessionId;
    }

\ueditor\net\App_Code\UploadHandler.cs 要修改的地方

public UploadHandler(HttpContext context, UploadConfig config)
            : base(context)
        {
            var sid = context.Request["sid"];
            config.SessionId = sid;
            this.UploadConfig = config;
            this.Result = new UploadResult() { State = UploadState.Unknown };
        }
public override void Process()
        {

            //所有编辑器的上传禁止
            //return;
            byte[] uploadFileBytes = null;
            string uploadFileName = null;

            if (UploadConfig.Base64)
            {
                uploadFileName = UploadConfig.Base64Filename;
                uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]);
            }
            else
            {
                var file = Request.Files[UploadConfig.UploadFieldName];
                uploadFileName = file.FileName;

                if (!CheckFileType(uploadFileName))
                {
                    Result.State = UploadState.TypeNotAllow;
                    WriteResult();
                    return;
                }
                if (!CheckFileSize(file.ContentLength))
                {
                    Result.State = UploadState.SizeLimitExceed;
                    WriteResult();
                    return;
                }

                uploadFileBytes = new byte[file.ContentLength];
                try
                {
                    file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
                }
                catch (Exception)
                {
                    Result.State = UploadState.NetworkError;
                    WriteResult();
                }
            }

            Result.OriginFileName = uploadFileName;

            //var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);
            //var localPath = Server.MapPath(savePath);
            //try
            //{
            //    if (!Directory.Exists(Path.GetDirectoryName(localPath)))
            //    {
            //        Directory.CreateDirectory(Path.GetDirectoryName(localPath));
            //    }
            //    File.WriteAllBytes(localPath, uploadFileBytes);
            //    Result.Url = savePath;
            //    Result.State = UploadState.Success;
            //}
            //catch (Exception e)
            //{
            //    Result.State = UploadState.FileAccessError;
            //    Result.ErrorMessage = e.Message;
            //}
            //finally
            //{
            //    WriteResult();
            //}

            try
            {
                string fileName = uploadFileName;
                string fileExt = System.IO.Path.GetExtension(fileName).ToLower().Replace(".", "");
                var type = 97;
                var url =App_Codes.GlobalMe.PicUploadServerUrl + "?sid={0}&t={1}&f={2}".Formats(UploadConfig.SessionId, type, fileExt);
                //Log.Info("UploadConfig=" + UploadConfig.ToJson());
                //Log.Info("url=" + url);
                //Log.Info("uploadFileBytes=" + uploadFileBytes.Length);
                //var str = Utility.Web.Http.Post(url, uploadFileBytes);
                //Log.Info("uploadFileBytes=" + uploadFileBytes.Length);

                var str = Utility.Web.Http.Post(url, uploadFileBytes, null, null, null, true, 5000);

                //Log.Info("result=" + str);
                var result = str.JsonToObject<App_Codes.UploadResult>();

                if (result != null && result.succeed)
                {
                    Result.Url = App_Codes.GlobalMe.NewsPicPrex + result.msg;
                    Result.State = UploadState.Success;
                }
                else
                {
                    Result.State = UploadState.NetworkError;
                    Result.ErrorMessage = "请重新登录";
                }
            }
            catch (Exception e)
            {
                Result.State = UploadState.FileAccessError;
                Result.ErrorMessage = e.Message;
            }
            finally
            {
                WriteResult();
            }
        }

细节未贴出,思路就是在处理图片的过程中把登录token要传下去,最后通过图片处理接口处理完图片,得到图片地址,返回给前端;

8 ueditor编辑器自动生成&nbsp解决办法

解决方法:

在ueditor.all.js文件找到上述所示代码,将&nbsp;替换为‘ ’即可。如下所示:

function isText(node, arr) {

        if(node.parentNode.tagName == 'pre'){
            //源码模式下输入html标签,不能做转换处理,直接输出
            arr.push(node.data)
        }else{
            arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,'&nbsp'))
        }

}

9 webp格式图片不能上传问题

ueditor默认不支持webp格式图片,找到 \ueditor\net\config.json 在里找到支持图片格式的地方,加上相关配置即可。

10 上传图片被自动压缩问题

在上传图片时发现大图片被自动压缩了,如果不想被压缩,可以修改 \ueditor\net\config.json 在里找到 "imageCompressEnable": true, /* 是否压缩图片,默认是true */ 改为false即可。

=== end ===

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值