vue-quill-editor 不允许粘贴图片但允许粘贴带背景色及颜色的文字
vue-quill-editor 富文本编辑器
今天被问到一个问题,拿来分享一下,网上有很多vue-quill-editor富文本编辑器不允许粘贴图片的解决方案,但基本上都一并不允许粘贴文字的背景色及文字颜色,下面将解决这个问题。
vue-quill-editor 如何禁止粘贴图片
data() {
return {
imageUrl: '',
editeContent: '',
editorOption: {
modules: {
clipboard: {
// 粘贴版,处理粘贴时候的自带样式
matchers: [[Node.ELEMENT_NODE, this.HandleCustomMatcher]],
},
toolbar: {
container: toolbarOptions, // 工具栏
handlers: {
image: function(value) {
if (value) {
// 获取隐藏的上传图片的class,不一定是.el-icon-plus。触发上传图片事件
document.querySelector('.el-icon-plus').click()
} else {
this.quill.format('image', false)
}
},
},
},
},
placeholder: '',
},
}
},
上面代码划重点:
clipboard: {
// 粘贴版,处理粘贴时候的自带样式
matchers: [[Node.ELEMENT_NODE, this.HandleCustomMatcher]],
},
方法代码:
// 添加匹粘贴板事件禁止图片粘贴
handleCustomMatcher (node, Delta) {
console.log(Delta)
const ops = []
Delta.ops.forEach(op => {
if (op.insert && typeof op.insert === 'string') { // 如果粘贴了图片,这里会是一个对象,所以可以这样处理
ops.push({
insert: op.insert // 文字内容
})
} else {
alert('不允许粘贴图片')
}
})
Delta.ops = ops
return Delta
}
vue-quill-editor 如何怎样允许或者粘贴文字样式
以上代码完美的禁止了富文本编辑器粘贴图片,但也一并把粘贴的文字的样式去掉了,其实只要加一句话就解决了,下面是代码:
// 添加匹粘贴板事件禁止图片粘贴
handleCustomMatcher (node, Delta) {
const ops = []
Delta.ops.forEach(op => {
console.log(op)
if (op.insert && typeof op.insert === 'string') { // 如果粘贴了图片,这里会是一个对象,所以可以这样处理
ops.push({
insert: op.insert, // 文字内容
attributes: op.attributes //文字样式(包括背景色和文字颜色等)
})
} else {
alert('不允许粘贴图片')
}
})
Delta.ops = ops
return Delta
}
上面代码划重点:
attributes: op.attributes //文字样式(包括背景色和文字颜色等)
以上是本文章全部内容,撒花。