TinyMCE的计数器无法正常工作

时间:2019-05-10 18:08:38

标签: javascript jquery html tinymce-3 richtextarea

我知道那里有很多解决方案,但是找不到正确的解决方案。我已经在tinyMCE版本3中为自定义计数器编写了代码,该版本的maxlength属性不起作用。我想在计数器达到0时停止提供更多文本,我使用过setcontent("")substring(0,maxcount)这似乎是有问题的,因为当我在修剪后两个字符之间输入任意2个字符时,不应这条路。我也尝试过使用evt.preventDefault()来防止,但无法再次输入IN进行击键,而击键也排除了bacspace和delete,但无法正常工作。 这是我的代码。

    tinyMCE.init({
        mode: "textareas",
        theme: "advanced",
        editor_selector: "mceEditor",
        paste_auto_cleanup_on_paste: 'true',
        theme_advanced_disable: 'justifyleft,justifyright,justifyfull,justifycenter,indent,image,anchor,sub,sup,unlink,outdent,help,removeformat,link,fontselect,hr,styleselect,formatselect,charmap,separator,code,visualaid,strikethrough,fullscreen',
        theme_advanced_buttons1: 'bold,italic,underline,numlist,bullist,undo,redo,cleanup,spellchecker',
        theme_advanced_buttons2: "",
        theme_advanced_buttons3: "",
        plugins: 'spellchecker,fullscreen,paste',
        spellchecker_languages: '+English=en-us',
        spellchecker_rpc_url: '<%out.print(request.getContextPath());%>/jazzy-spellchecker',
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_path : false,
        statusbar: true,
        setup: function(editor)
        {
             editor.onKeyUp.add(function(evt)
            {
                var maxLengthRichTextArea = 5;
                 var inputRichTextArea = $(editor.getBody()).text();
                 var inputRichTextAreaLength = inputRichTextArea.length;
                 var value = maxLengthRichTextArea-inputRichTextAreaLength;
                 if(value >= 0)
                 {  
                 $(tinyMCE.activeEditor.getContainer()).find("#"+editor.id+"_path_row").html("Remaining chars: "+(value));
                }           
                if(inputRichTextAreaLength > maxLengthRichTextArea) {
                 editor.setContent("");
                tinyMCE.activeEditor.selection.setContent(inputRichTextArea.substring(0, maxLengthRichTextArea));
                }                  
            });
        }
    });

</script>

HTML

<textarea id="450225" class="mceEditor"  maxlength="10" style="display: none;"></textarea>

This is working good

But here when I add 6 its triimming of last digit 5

如何解决此问题,最大数量实际上是来自数据库的更高数量。

1 个答案:

答案 0 :(得分:7)

这是您要实现的目标的有效示例:

HTML:

<textarea id="text"></textarea>

JavaScript:

tinymce.init({
  selector: "textarea#text",
  height: 500,
  menubar: false,
  setup: function(editor) {
    var maxlength = 5;
    var allowedKeys = [8, 37, 38, 39, 40];
    editor.on("keydown", function(e) {
      var count = $(editor.getBody()).text().length;
      if(allowedKeys.indexOf(e.which) != -1) {
         return;
      }
      if (count >= maxlength) {
        e.stopPropagation();
        return false;
      }
    });
  }
});

还有codepen,希望对您有所帮助!在我的代码中,最大长度为5,但是您可以通过变量maxlength进行更改。

相关问题