介绍
wangEditor是一个轻量级 web 富文本编辑器,配置方便,使用简单。
官网:
文档:/doc
源码:/wangeditor-team/wangEditor
用于 Vue 和 React
在 Vue 中使用 wangEditor
vue3 可参考 wangEditor-with-vue3
vue2 可参考 wangEdior-with-vue 。
在 React 中使用 wangEditor
如果要自己动手开发,可参考 wangEditor-with-react 。
如果想要用现成的插件,可参考 wangeditor-for-react 。
下载
下载
npm 安装 npm i wangeditor --save
CDN 链接 /npm/wangeditor@latest/dist/wangEditor.min.js
基本使用
NPM
npm i wangeditor --save
安装后几行代码即可创建一个编辑器:
import E from "wangeditor"const editor = new E("#div1")editor.create()
常用的设置
设置编辑区域的高度
编辑区域高度默认为 300px ,可通过以下方式修改。
const editor = new E('#div1')// 设置编辑区域高度为 500pxeditor.config.height = 500// 注意,先配置 height ,再执行 create()editor.create()
菜单和编辑区域分离
菜单和编辑区域其实就是两个单独的
,位置、尺寸都可以随便定义。
<head><style>.toolbar {border: 1px solid #ccc;}.text {border: 1px solid #ccc;min-height: 400px;}</style></head><body><p>container 和 toolbar 分开</p><div><div id="toolbar-container" class="toolbar"></div><p>------ 我是分割线 ------</p><div id="text-container" class="text"></div></div><!-- 引入 wangEditor.min.js --><script>const E = window.wangEditorconst editor = new E('#toolbar-container', '#text-container') // 传入两个元素editor.create()</script></body>
一个页面多个编辑器
在页面只使用一个编辑器时可以使用ref获取页面元素,页面有两个编辑器的时候用id获取页面元素。
<head><style type="text/css">.toolbar {background-color: #f1f1f1;border: 1px solid #ccc;}.text {border: 1px solid #ccc;height: 200px;}</style></head><body><div id="div1" class="toolbar"></div><div style="padding: 5px 0; color: #ccc">中间隔离带</div><div id="div2" class="text"><p>第一个 demo(菜单和编辑器区域分开)</p></div><div id="div3"><p>第二个 demo(常规)</p></div><!-- 引入 wangEditor.min.js --><script type="text/javascript">const E = window.wangEditorconst editor1 = new E('#div1', '#div2')editor1.create()const editor2 = new E('#div3')editor2.create()</script></body>
如果在控制台报错“找不到节点”,要注意是不是使用了v-if将页面元素隐藏了导致获取不到DOM节点。两个编辑器要注意命名冲突和使用位置。
设置内容
html 初始化内容(尽量使用这种方式)
直接将内容写到要创建编辑器的
标签中。
<div id="div1"><p>初始化的内容</p><p>初始化的内容</p></div><!-- 引入 wangEditor.min.js --><script type="text/javascript">const E = window.wangEditorconst editor = new E('#div1')editor.create()</script>
js 设置内容
创建编辑器之后,使用 editor.txt.html(…) 设置编辑器内容。
<div id="div1"></div><!-- 引入 wangEditor.min.js --><script type="text/javascript">const E = window.wangEditorconst editor = new E('#div1')editor.create()editor.txt.html('<p>用 JS 设置的内容</p>') // 重新设置编辑器内容</script>
追加新内容
创建编辑器之后,可使用editor.txt.append('<p>追加的内容</p>')
继续追加内容。
获取 html
使用 editor.txt.html() 获取 html 。
需要注意的是:从编辑器中获取的 html 代码是不包含任何样式的纯 html。
获取 text
使用 editor.txt.text() 获取 text 文本。
清空内容
可使用 editor.txt.clear() 清空编辑器内容。