How to add a non editable tag to content in Quill editor

别来无恙 提交于 2019-12-01 03:42:34

You should be able to achieve this by writing your own Blot:

class Label extends Parchment.Embed {
  static create(value) {
    const node = super.create(value);
    node.innerText = value;
    // Remember to set this so users can't edit
    // the label's content
    node.contentEditable = 'false';
    this._addRemovalButton(node);
    return node;
  }

  static value(node) {
    // Only return the text of the first child
    // node (ie the text node), otherwise the
    // value includes the contents of the button
    return node.childNodes[0].textContent;
  }

  static _addRemovalButton(node) {
    const button = document.createElement('button');
    button.innerText = 'x';
    button.onclick = () => node.remove();
    button.contentEditable = 'false';
    node.appendChild(button);

    // Extra span forces the cursor to the end of
    // the label, otherwise it appears inside the
    // removal button
    const span = document.createElement('span');
    span.innerText = ' ';
    node.appendChild(span);
  }
}
Label.blotName = 'label';
Label.tagName = 'SPAN';
Label.className = 'ql-label';

You register it with Quill:

Quill.register(Label);

And finally, you can use it in a similar way to an image or other embeds:

quill.updateContents(
  new Delta().insert({ label: 'foo' })
);

NB: Any styling you need can be applied with the .ql-label class:

.ql-label {
  background-color: lightgrey;
  padding: 0.3em;
  margin: 0 0.2em;
}

.ql-label button {
  margin-left: 0.3em;
}

Finally finally: a working example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!