首先确定你用的是下面这个编辑器,Quill官网
实现效果参考:
然后开始了
配置toolbarOptions
默认的全量配置
const toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
['link', 'image', 'video', 'formula'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered'}, { 'list': 'bullet' }, { 'list': 'check' }],
[{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'] // remove formatting button
];
参考:Toolbar Module - Quill Rich Text Editor (quilljs.com)
在toolbar配置中添加自己的功能(如:media)
function initEditor(){
const toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
['link', 'image', 'video', 'formula'],
// [{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered'}, { 'list': 'bullet' }, { 'list': 'check' }],
[{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
[{ 'direction': 'rtl' }], // text direction
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'font': [] }],
[{ 'align': [] }],
['clean'], // remove formatting button
['media']
];
如上所示,最后一个地方添加了一个media节点。
const quill = new Quill('#editor', {
theme: 'snow',
modules:{
toolbar:{
container:toolbarOptions,
handlers:{
media:function (){
alert('打开媒体库,插入了一个图片链接');
let index = quill.selection.savedRange.index; // 获取光标位置
quill.insertEmbed(index, 'image', 'https://cdn.pixabay.com/photo/2023/11/14/20/08/woman-8388428_1280.jpg');
// 重新计算index
//注意如果是文本内容则需要计算文本长度 index = text.length;
index+=1
// 移动光标至文本后面
quill.setSelection(index);
}
}
},
}
});
/**
* 初始化自定义按钮
*/
function initCustomToolbarBtn(){
//css '.ql-' + 'toolbar里面配置的btn名称'
let mediaBtn = document.querySelector('.ql-media');
let elementI=document.createElement('i');
// elementI.classList.add('fa-solid fa-image'); //error
elementI.classList='fa-solid fa-image';
// elementI.style.cssText="width:80px; border:1px solid #ccc; border-radius:5px;"
elementI.title='打开媒体库';
mediaBtn.appendChild(elementI)
}
https://blog.xqlee.com/article/2408020955485956.html