导航
百度富文本编辑器(UEditor)
UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码。
基本demo
- 进入ueditor官网下载压缩包,解压后就是ueditor的基本demo,包含了ueditor所需要的js css等文件
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>完整demo</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript" charset="utf-8" src="ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="ueditor.all.min.js"> </script>
<!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->
<!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
<script type="text/javascript" charset="utf-8" src="lang/zh-cn/zh-cn.js"></script>
<style type="text/css">
div{
width:100%;
}
</style>
</head>
<body>
<div>
<script id="editor" type="text/plain" style="width:1024px;height:500px;">
</script>
</div>
<script type="text/javascript">
//实例化编辑器
//建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例
var ue = UE.getEditor('editor');
</script>
</body>
</html>
基本API
- 获得整个html的内容
UE.getEditor('editor').getAllHtml()
- 获得内容(带有元素标签 但是不包含整个html)
UE.getEditor('editor').getContent()
- 写入内容
UE.getEditor('editor').setContent('欢迎使用ueditor')
- 追加内容
UE.getEditor('editor').setContent('欢迎使用ueditor', true)
- 获得纯文本
UE.getEditor('editor').getContentTxt()
- 获得带格式的纯文本(空格,换行)
UE.getEditor('editor').getPlainTxt()
- 判断是否有内容
UE.getEditor('editor').hasContents()
- 使编辑器获得焦点
UE.getEditor('editor').focus();
- 使编辑器获得焦点
UE.getEditor('editor').focus();
- 编辑器是否获得焦点
UE.getEditor('editor').isFocus()
- 编辑器失去焦点
UE.getEditor('editor').blur()
- 获得当前选中的文本
//当你点击按钮时编辑区域已经失去了焦点,如果直接用getText将不会得到内容,所以要在选回来,然后取得内容
var range = UE.getEditor('editor').selection.getRange();
range.select();
var txt = UE.getEditor('editor').selection.getText();
- 插入给定的内容
UE.getEditor('editor').execCommand('insertHtml', '<div>插入给定的内容</div>')
- 其他
//可以编辑
UE.getEditor('editor').setEnabled()
//不可编辑
UE.getEditor('editor').setDisabled('fullscreen');
//隐藏编辑器
UE.getEditor('editor').setHide()
//显示编辑器
UE.getEditor('editor').setShow()
//设置高度为300默认关闭了自动长高
UE.getEditor('editor').setHeight(300)
//获取草稿箱内容
UE.getEditor('editor').execCommand( "getlocaldata" )
//清空草稿箱
UE.getEditor('editor').execCommand( "clearlocaldata" )
其余相关api请参考UEditor Docs
拓展相关
- 图片上传配置
在页面中配置你的图片上传路径
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
// 为方法imgUpload的访问地址
return '你的上传路径';
} else if (action == 'uploadfile' ){
//上传附件的访问地址