前言
本文主要使用CKEditor4版本
CKEditor4
下载地址
https://ckeditor.com/ckeditor-4/download/
官方文档
https://ckeditor.com/docs/ckeditor4/latest/guide/dev_installation.html
使用CKEditor
把下载的包放在 public
文件夹下
index.html
中添加
1 | <script type="text/javascript" src="./ckeditor/ckeditor.js"></script> |
页面中
1 | <div class="warp_editor"> |
样式
1 | .warp_editor { |
初始化
1 | window.CKEDITOR.inline('editor', {height: '300px', width: '100%', toolbar: 'full'}) |
或者
1 | window.CKEDITOR.replace('editor', {height: '300px', width: '100%', toolbar: 'full'}) |
取值赋值
获取富文本
1 | let html1 = window.CKEDITOR.instances["editor"].getData(); |
获取纯文本内容:
1 | // inline模式(div包含) |
如果要赋值那么就是
1 | myeditor.setData("需要赋值的内容"); |
监听值变化
1 | let myeditor = window.CKEDITOR.inline('editor', {height: '100%', width: '100%', toolbar: 'full'}) |
图片转base64
1 | CKEDITOR.replace('description'); |
本地文件转Base64
1 | function changeBase64(url) { |
自定义Vue组件
两种方式都要注意在组件销毁的时候删除DOM。
InlineEditor
无论是粘贴图片还是上传都转为Base64。
InlineEditor.vue
1 | <template> |
使用
1 | <template> |
CommonEditor
实现了无论粘贴图片还是上传图片都保存到服务器上。
CommonEditor.vue
1 | <template> |
使用ckeditor4-vue
这种方式支持的功能较少
并且扩展性不好,建议自己引用
结合VUE
1 | npm install --save ckeditor4-vue |
main.js引入
1 | import CKEditor from 'ckeditor4-vue'; |
页面中
1 | <template> |
上传图片到服务器
默认的编辑器配置是支持粘贴的图片自动转Base64的
要想图片上传至服务器就要把 config.js中添加
1 | config.filebrowserImageUploadUrl = ""; |
如下
1 | CKEDITOR.editorConfig = function (config) { |
上传图片转Base64
默认的编辑器配置是支持粘贴的图片自动转Base64的
我们想点击图片上传按钮后选中图片确定也用base64保存,就要自定义插件。
在plugins
文件夹下添加zimage
文件夹
添加以下文件
plugins/zimage/plugin.js
plugins/zimage/dialog/dialog.js
plugins/zimage/icons/zimage.png
注意其中
第1项名称不能变。
第3项的图片名称要和定义插件时指定的名称相同,建议使用插件的名称。
plugins/zimage/plugin.js
1 | CKEDITOR.plugins.add('zimage', { |
plugins/zimage/dialog/dialog.js
1 | CKEDITOR.dialog.add('zimageDialog', function (editor) { |
config.js
中extraPlugins
添加我们的插件名
如下
1 | CKEDITOR.editorConfig = function (config) { |
DIV获取焦点
div
在正常情况下是无法获得焦点的,而我们常用的blur()和focus()多是常用于input
,对于div
都是没有用的。让一个div
获取焦点,其解决方案如下:
增加:tabindex = "-1"
如:
1 | <div class="icon-change" tabindex="-1" @blur="colorShow"></div> |
然后继续写失焦和聚焦事件就好了。
tabindex属性:
- html中的tabIndex属性可以设置键盘中的TAB键在控件中的移动顺序,即焦点的顺序。把控件的tabIndex属性设成1到32767的一个值,就可以把这个控件加入到TAB键的序列中。
- 当浏览者使用TAB键在网页控件中移动时,将首先移动到具有最小tabIndex属性值的控件上,最后在具有最大tabIndex属性值的控件上结束移动。
- 如果有两个控件的tabIndex属性相同,则以控件在html代码中出现的顺序为准。
- 默认的tabIndex属性为 0,将排列在在所有指定tabIndex的控件之后。
- 而若把tabIndex属性设为一个负值(如
tabIndex="-1"
),那么这个链接将被排除在TAB键的序列之外。 - 注意:如果使用-1值时,onfocus与onblur事件仍被启动。
如果想让编辑器鼠标移开自动取消焦点可以
1 | dom_scroll_event() { |
触发事件
触发事件
1 | function FireEvent(elem, eventName) { |
调用
1 | FireEvent(document.getElementById('id'), 'change') |
HTML处理
1 | let newhtml = data.html.replace(/<(?!img|p|\/p).*?>/g, ""); |
常见错误
1 | Error code: pastetools-unsupported-image. {type: 'image/wmf', index: 0} |