CKEditor 5富文本编辑器使用教程(一)

Winter

2019-03-14

如果你正在开发博客网站,正愁于用什么插件来做文章编辑,那么可以考虑使用CKEditor。

一般设计文章编辑都希望用的富文本编辑器有以下功能

  • 样式丰富,便于设置文本样式
  • 扩展方便,可以对富文本进行功能扩展,实现需要的功能
  • 可定制化,富文本的样式可以定制以适应于各个场景

我的网站https://SamYoc(https://www.samyoc.com)富文本编辑器使用的正是CKEditor,不过用的是CKEditor 4。但是今天我们要说的是CKEditor 5。

CKEditor 5对于CKEditor 4来说,有着显著的提高

  • 更加美观,视觉上看确实如此
  • 定制化程度高
  • 组件化建设程度更高

那么话不多说,先来看看CKEditor的几种形态。

Classic editor (经典版)

经典版的顶部会常驻工具栏。

Inline editor(内联版)

这个形态的编辑器与classic的相比最大的不同在于顶部的工具栏不会常驻,用户只要进入编辑状态,才会显示出工具栏,就像这样。但是工具栏只会浮动出现在顶部

Balloon block editor

这个形态是顶部工具栏也不会常驻,但是和Inline editor不同点在于,工具栏的位置是跟随你的编辑光标位置动态变化。而且左侧有一个音符,点击这个音符可以弹出工具栏。

Balloon editor

这个形态和Balloon block editor是一样的,不同点在于左侧没有了这个音符。

上面这些形态基本也够我们使用了。详细的信息还可以看官方文档:CKEditor Ecosystem Documentation

 

下面再来看一下最基础的使用。有以下几种使用方式

1. 无脑使用,插件里提供什么,我就用什么

这是一种比较懒的使用方式,要做的事情也是极其简单的,下面以Classic Editor为例。

在你的HTML页面中加一个textarea元素,CKEditor会对它做处理:

 <textarea name="content" id="editor"></textarea>

加载 classic editor build (here CDN location is used):

 <script src="https://cdn.ckeditor.com/ckeditor5/12.0.0/classic/ckeditor.js"></script>

Call the ClassicEditor.create() method.


 <script>
ClassicEditor .create( document.querySelector( '#editor' ) ) .catch( error => {
  console.error( error ); 
} ); </script>

示例:

 


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CKEditor 5 – Classic editor</title>
    <script src="https://cdn.ckeditor.com/ckeditor5/12.0.0/classic/ckeditor.js"></script>
</head>
<body>
    <h1>Classic editor</h1>
    <textarea name="content" id="editor">
        <p>This is some sample content.</p>
    </textarea>
    <script>
        ClassicEditor
            .create( document.querySelector( '#editor' ) )
            .catch( error => {
                console.error( error );
            } );
    </script>
</body>
</html>

ES6版本

npm install --save @ckeditor/ckeditor5-build-classic

现在在你的代码中import:

// Using ES6 imports:
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';

// Or CJS imports:
const ClassicEditor = require( '@ckeditor/ckeditor5-build-classic' );

使用方法:

ClassicEditor
    .create( document.querySelector( '#editor' ) )
    .then( editor => {
        console.log( editor );
    } )
    .catch( error => {
        console.error( error );
    } );

2.定制化,增加自定义插件,使用指定插件

将会在下一篇揭晓...

第114篇《CKEditor 5富文本编辑器使用教程(一)》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4条评论
小秦 2023.07.07

我的表格没有功能

醒不来的梦° 2020.12.02

不能图片上传啊

可以图片上传,不过要自己适配一下

Winter 2020.12.03
Clover 2020.09.28

你加过代码块功能吗

加过额,你可以试试本网站的写文章里面就有代码块功能,体验一下,这个就是ckeditor的

Winter 2020.09.28
难. 2020.07.14

您好我想问一下,为啥我把经典版的cdn换成气球的就不行了

 

换成气球的是啥意思,不过不同版对应的cdn链接是不同的噢

Winter 2020.07.14