温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - TinyMCE, show character count instead of word count
javascript jquery tinymce charactercount

javascript - TinyMCE,显示字符数而不是字数

发布于 2020-04-29 20:42:54

标题说明了一切。如何使TinyMCE显示字符数而不是字数?

在此处输入图片说明

查看更多

提问者
Rust
被浏览
7
naXa 2019-08-21 23:12

编写自己的插件。

以下解决方案基于本文charactercount插件计算的实际字符用户可以看到,所有的HTML和隐藏字符被忽略。该数字在每次“按键”事件时更新。

字符计数插件:

tinymce.PluginManager.add('charactercount', function (editor) {
  var self = this;

  function update() {
    editor.theme.panel.find('#charactercount').text(['Characters: {0}', self.getCount()]);
  }

  editor.on('init', function () {
    var statusbar = editor.theme.panel && editor.theme.panel.find('#statusbar')[0];

    if (statusbar) {
      window.setTimeout(function () {
        statusbar.insert({
          type: 'label',
          name: 'charactercount',
          text: ['Characters: {0}', self.getCount()],
          classes: 'charactercount',
          disabled: editor.settings.readonly
        }, 0);

        editor.on('setcontent beforeaddundo', update);

        editor.on('keyup', function (e) {
            update();
        });
      }, 0);
    }
  });

  self.getCount = function () {
    var tx = editor.getContent({ format: 'raw' });
    var decoded = decodeHtml(tx);
    // here we strip all HTML tags
    var decodedStripped = decoded.replace(/(<([^>]+)>)/ig, "").trim();
    var tc = decodedStripped.length;
    return tc;
  };

  function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
  }
});

CSS调整:

/* Optional: Adjust the positioning of the character count text. */
label.mce-charactercount {
  margin: 2px 0 2px 2px;
  padding: 8px;
}

/* Optional: Remove the html path code from the status bar. */
.mce-path {
  display: none !important;
}

TinyMCE初始化(使用jQuery)

$('textarea.tinymce').tinymce({
  plugins: "charactercount",
  statusbar: true,
  init_instance_callback: function (editor) {
    $('.mce-tinymce').show('fast');
    $(editor.getContainer()).find(".mce-path").css("display", "none");
  }
  // ...
});

ps。使用JS缩小器。