如何在我的Quill项目中添加角色计数器?

时间:2018-12-21 02:54:02

标签: javascript html quill

因此,我必须创建一个Quill接口来进行分配。必须有一个单词计数器,但我发现我还需要一个针对所有字符的计数器。 那么将这个字符计数器添加到我的项目中的最佳方法是什么。

    class Counter {
      constructor(quill, options) {
        this.quill = quill;
        this.options = options;
        this.container = document.querySelector(options.container);
        quill.on('text-change', this.update.bind(this));
        this.update();  // Account for initial contents
      }

      calculate() {
        let text = this.quill.getText();
        if (this.options.unit === 'word') {
          text = text.trim();
          // Splitting empty text returns a non-empty array
          return text.length > 0 ? text.split(/\s+/).length : 0;
        } else {
          return text.length;
        }
      }

      update() {
        var length = this.calculate();
        var label = this.options.unit;
        if (length !== 1) {
          label += 's';
        }
        this.container.innerText = length + ' ' + label;
      }
    }

    Quill.register('modules/counter', Counter);

    var quill = new Quill('#editor', {
      modules: {
        toolbar: toolbarOptions,
        counter: {
          container: '#counter',
          unit: 'word'
        }
      },
        theme: 'snow'
    });

3 个答案:

答案 0 :(得分:0)

该指南有一个教程,用于编写一个基于config选项对单词或字符进行计数的模块: https://quilljs.com/guides/building-a-custom-module/#using-options

var quill = new Quill('#editor', {
  modules: {
    counter: {
      container: '#counter',
      unit: 'character'
    }
  }
});

演示: https://codepen.io/anon/pen/vPRoor

答案 1 :(得分:0)

在示例中,https://codepen.io/anon/pen/vPRoor

字符计数默认情况下以1开头。相反,它应该以0开头。这可以通过在calculate函数中添加trim方法来完成。

更改:

calculate() {
let text = this.quill.getText();

收件人:

 calculate() {
 let text = this.quill.getText().trim();

答案 2 :(得分:0)

quill.on('text-change', function () {

    const limted = 10;
    const totalChar = quillEditor.getLength() - 1;

    if (quillEditor.getLength() > limted + 1)
        quillEditor.deleteText(limted, totalChar);
    else
        chCounter.text(totalChar)
});