引用js
<script src="//cdn.ckeditor.com/ckeditor5/12.3.1/classic/ckeditor.js"></script>
<script src="//cdn.ckeditor.com/ckeditor5/12.3.1/classic/translations/zh-cn.js"></script>
前端代码
<div id="content" name="content">
</div>
核心js
//编辑器editor
ClassicEditor
.create(document.querySelector('#content'), {
language: 'zh-cn',
ckfinder: {
uploadUrl: 'CKEditor/Upload'
}
})
.then(editor => {
window.editor = editor;
//监听提交
form.on('submit(layuiadmin-article-submit)', function (data) {
var field = data.field; //获取提交的字段
//获取编辑器内容
const content = editor.getData();
if (!content)
return layer.msg("请编辑内容", { icon: 2 });
if (!content)
return layer.msg("内容不可为空", { icon: 2 });
field = Object.assign(field, { content: content });
admin.req({
url: 'article/add'
, type: 'post'
, data: { info: field }
, done(res) {
layer.close(index);
layui.table.reload('LAY-article-list'); //重载表格
//提交完毕销毁editor
editor.destroy().catch(error => {
console.log(error);
});
}
});
});
form.render();
})
.catch(error => {
console.error(error);
});
核心方法
//获取ckeditor内容
var content = editor.getData();
//设置ckeditor内容
editor.setData(content);
//设置ckeditor编辑器为只读
editor.isReadOnly = true;
在文章详情页中展示保存的内容的示例(C# MVC中使用)
<input id="txt_content" type="hidden" value="@newsInfo.Content" />
<div id="content"></div>
<script src="//cdn.ckeditor.com/ckeditor5/12.3.1/classic/ckeditor.js"></script>
<script>
ClassicEditor
.create(document.querySelector('#content'), {
toolbar: []
})
.then(editor => {
window.editor = editor;
editor.isReadOnly = true;
editor.setData(document.getElementById('txt_content').value);
document.getElementsByClassName('ck-toolbar').item(0).remove();
})
.catch(error => {
console.error(error);
});
</script>
后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace WebApplication.Controllers
{
public class CKEditorController : Controller
{
public IActionResult Upload(List<IFormFile> files)
{
//https://ckeditor.com/docs/ckeditor5/latest/framework/guides/deep-dive/upload-adapter.html
var req = Request;
Dictionary<string, string> dic = new Dictionary<string, string>()
{
{ "uploaded" , "true" },
{ "url" , "/favicon.ico" }
};
return Json(dic);
}
}
}