ASP.NET中集成百度编辑器UEditor

UEditor是由百度WEB前端研发部开发的所见即所得的开源富文本编辑器,具有轻量、可定制、用户体验优秀等特点。开源基于BSD协议,所有源代码在协议允许范围内可自由修改和使用。

UEditor官网:

UEditor官方文档地址:

1.将ueditor包导入项目

将从官网上下载的开发包解压后包含到项目中

(注:最新的代码需要时基于.NETFramework4以上)

解压后目录下文件如下:

index.html 是一个示例文件、可以删去,ueditor.config.js中是一些富文本编辑器的设置,建议不要改动,可以在页面中引用的时候设置,如果所有页面都需要设置可以写在一个js文件中,dialogs是在文本框中点击按钮时用到的一些弹出框效果,lang文件夹下是语言相关的设置,目前只有中文与英文,themes文件夹下是一些样式,third-party文件夹下是一些第三方的插件,有代码高亮,截屏等

ASP.NET中集成百度编辑器UEditor

我在我的项目中新建了一个ueditorHelper.js文件,在文件中定义了一些ueditor常用的方法,以及对于ueditor的一些设置

ASP.NET中集成百度编辑器UEditor

ASP.NET中集成百度编辑器UEditor

在net目录下,我们只保留controller.ashx与config.json就可以了,同时把App_Code中的代码拷贝到项目中的App_Code中,同时添加对bin目录下Json.NET程序集的引用,config.json文件定义了一些设置,配置上传文件的一些要求以及上传到服务器保存的路径,在web.config文件中可以看到项目框架应至少为4.0

2.在页面中添加js引用,在页面中引用

ASP.NET中集成百度编辑器UEditor

添加zh-cn.js文件是要设置语言,防止自动识别语言错误而导致语言适配错误,UEditorHelper.js文件是一些常用的方法和编辑器设置的封装,查看index.html的源代码,在其中有一段js代码

ASP.NET中集成百度编辑器UEditor

自定义的UEditorHelper.js文件中使用到了一些方法,并对第一行代码进行了修改,进行 ueditor富文本编辑器的设置

ASP.NET中集成百度编辑器UEditor

3.页面初始化

在需要添加富文本编辑器的地方加入以下代码:

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

4.编辑内容时,页面的加载(ajax加载内容)

因为富文本编辑器只是生成的一段html代码,我们需要利用Ajax动态加载内容,相比CKEditor来说,这是比较麻烦的地方,使用CKEditor可以直接使用封装好的服务器端控件,当然也可以不用服务器端控件利用Ajax动态加载内容。

首先在页面加载时获取到新闻的id,然后再进行ajax查询,查询新闻封装在了一个handler中,向这个handler发起ajax请求,请求参数为新闻id,获取新闻,获取到之后,把新闻的内容设置给ueditor

ASP.NET中集成百度编辑器UEditor

//实例化编辑器 //建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例 var ue = UE.getEditor('editor',{autoHeightEnabled: false}); function isFocus(e) { alert(UE.getEditor('editor').isFocus()); UE.dom.domUtils.preventDefault(e) } function setblur(e) { UE.getEditor('editor').blur(); UE.dom.domUtils.preventDefault(e) } function insertHtml() { var value = prompt('插入html代码', ''); UE.getEditor('editor').execCommand('insertHtml', value) } function createEditor() { UE.getEditor('editor'); } function getAllHtml() { return UE.getEditor('editor').getAllHtml(); } function getContent() { return UE.getEditor('editor').getContent(); } function getPlainTxt() { return UE.getEditor('editor').getPlainTxt(); } function setContent(isAppendTo) { UE.getEditor('editor').setContent('', isAppendTo); } function getText() { //当你点击按钮时编辑区域已经失去了焦点,如果直接用getText将不会得到内容,所以要在选回来,然后取得内容 var range = UE.getEditor('editor').selection.getRange(); range.select(); return UE.getEditor('editor').selection.getText(); } function getContentTxt() { return UE.getEditor('editor').getContentTxt(); } function hasContent() { return UE.getEditor('editor').hasContents(); } function setFocus() { UE.getEditor('editor').focus(); } function deleteEditor() { UE.getEditor('editor').destroy(); } function getLocalData() { alert(UE.getEditor('editor').execCommand("getlocaldata")); } function clearLocalData() { UE.getEditor('editor').execCommand("clearlocaldata"); alert("已清空草稿箱") }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzygx.html