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

前端 未结 1 2111
傲寒
傲寒 2021-02-20 01:57

I want to add a couple of pre-built labels like

Label Text x

to the html conten

相关标签:
1条回答
  • 2021-02-20 02:39

    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.

    0 讨论(0)
提交回复
热议问题