首页 > 解决方案 > QuillJS:自定义 attr alt

问题描述

感谢您对我的问题感兴趣。

使用技术: PHP / JS

希望结果:我想允许将属性“alt”添加到图像中。添加图片时,发送到服务器,然后将带有 url (src) 的 img 标签插入到编辑器中。它完美地工作。

我想要的是当您在编辑器中单击图像时,我们会打开一个框

该框建议自定义属性“alt”,有点像在 quilljs 中自定义链接。

见图片:

在此处输入图像描述

问题:有人会遇到这种东西,如果不是我应该采取什么方法?有人知道我应该怎么做吗?

非常感谢你的回答。

标签: quill

解决方案


我做了这样的事情。首先,我创建自己的图像印迹

class CustomImage extends BlockEmbed {
  static create (value) {
    let node = super.create()
    let img = document.createElement('img')
    img.setAttribute('alt', value.alt || '')
    img.setAttribute('src', value.url)
    node.appendChild(img)
    return node
  }
static formats (node) {
    let format = {}
    // do something with format for example format.alt = node.setAttribute('alt')
    // it's need to save changes in Delta
    return format
}
// also need to define static value
static value (node) {
    return {
      alt: node.getAttribute('alt'),
      url: node.getAttribute('src')
    }
  }
// and "public" typical method in JS
format (name, value) {
  if (name === 'alt') {
    this.domNode.alt = value
  }
}

第二件事,我为图像创建简单的弹出设置(它只是html元素)并将其放入文档中。

然后我窥视了 quill 模块(quill-image-drop-module)它是如何以正确的方式实现的。我只是处理点击文档,如果点击是在img元素上触发的,我会向用户显示弹出窗口。

document.addEventListener('click', e => {
  if (e.target.tagName.toUpperCase() === 'IMG') {
    // just open popup and pass to it all settings from your blot image
    // for get all props from image use let blot = Parchment.find(e.target)
    // read more about this below
  }
}

要从图像中获取所有属性并更改它们,只需使用印迹对象。需要正常处理历史记录 (CTRL+Z)。不要直接更改图像DOM元素,使用印迹。因此,要获取所有属性并使用它们,请使用以下命令:

import Parchment from 'parchment'
let blot = Parchment.find(this.currentImg)
// blot contain all what you need, all properties
// and you can change them in this way:
blot.format('alt', e.target.value)

我希望它对你有帮助。这只是基本的实现,但我想,你了解下一步该做什么,以及它是如何工作的。

PS我不确定,这是最正确的方法,但我是这样做的。谢谢你。


推荐阅读