如何在Quill编辑器中向内容添加不可编辑的标记

pra*_*vin 8 wysiwyg wysihtml5 reactjs quill

我想添加一些预制的标签,如

<div class="label"> Label Text <span>x</span><div>
Run Code Online (Sandbox Code Playgroud)

到主播编辑器中的html内容.添加这样的标签本身不应该是一个问题.但是我不希望用户能够编辑标签内的文本.甚至不允许将光标放在标签内.在删除时,div应删除整体.在某种意义上,整个标签应该像一个图像.可能吗 ?

Ale*_*lec 10

您应该能够通过编写自己的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';
Run Code Online (Sandbox Code Playgroud)

你用 Quill注册它:

Quill.register(Label);
Run Code Online (Sandbox Code Playgroud)

最后,您可以以类似于 animage或其他embeds 的方式使用它:

quill.updateContents(
  new Delta().insert({ label: 'foo' })
);
Run Code Online (Sandbox Code Playgroud)

注意:您需要的任何样式都可以应用于.ql-label该类:

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';
Run Code Online (Sandbox Code Playgroud)

最后终于:一个工作示例