【发布时间】:2016-06-24 05:13:04
【问题描述】:
可以从 url 将图像添加到 quill JS 编辑器中,但无法像所有传统的富文本编辑器那样从计算机添加图像。
有什么方法可以达到这个目的吗?
【问题讨论】:
-
这会使用 url 添加图像。不允许从计算机拖放或添加图像
标签: javascript quill
可以从 url 将图像添加到 quill JS 编辑器中,但无法像所有传统的富文本编辑器那样从计算机添加图像。
有什么方法可以达到这个目的吗?
【问题讨论】:
标签: javascript quill
您可以执行以下操作:
quill.getModule("toolbar").addHandler("image", () => {
this.selectLocalImage();
});
function selectLocalImage() {
var input = document.createElement("input");
input.setAttribute("type", "file");
input.click();
// Listen upload local image and save to server
input.onchange = () => {
const file = input.files[0];
// file type is only image.
if (/^image\//.test(file.type)) {
this.saveToServer(file, "image");
} else {
console.warn("Only images can be uploaded here.");
}
};
}
function saveToServer(file) {
// Upload file to server and get the uploaded file url in response then call insertToEditor(url) after getting the url from server
}
function insertToEditor(url) {
// push image url to editor.
const range = quill.getSelection();
quill.insertEmbed(range.index, "image", url);
}
【讨论】:
这很简单。只需添加一个带有 ql-image 类的按钮。
下面的例子:
<div id="toolbar" class="toolbar">
<span class="ql-formats">
<button class="ql-image"></button>
</span>
</div>
最后,实例化 Quill 并将工具栏容器设置为您的工具栏元素:
var quill = new Quill('#editor', {
modules: {
toolbar: {
container: '#toolbar'
}
},
theme: 'snow'
});
这会将图像作为 img 元素上的 base 64 编码字符串添加到内容可编辑区域。
【讨论】: