javascript 在summernote中设置最大长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27527989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:35:30  来源:igfitidea点击:

Setting max length in summernote

javascriptjquerysummernote

提问by Reshma

How can I apply a maxlength to Summernote? Applying a maxlength to the textarea does not work here.

如何将最大长度应用于 Summernote?将 maxlength 应用于 textarea 在这里不起作用。

https://github.com/summernote/summernote

https://github.com/summernote/summernote

$("#textareaid").summernote({
      toolbar:[
        ['style', ['style']],
        ['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']],
        ['fontname', ['fontname']],     
        ['fontsize', ['fontsize']], 
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['height', ['height']],
        ['table', ['table']],
        ['insert', ['link', 'picture', 'video', 'hr']],
        ['view', ['fullscreen', 'codeview']],
        ['help', ['help']]      
      ],                  
      height: 250,  
      focus: true 
});

$("#summernotediv").code("");           
$('.note-help-dialog .row-fluid >p').hide();    
$('.note-editable').css('overflow','auto'); 
$('.note-image-input').prev('h5').remove();
$('.note-image-input').remove();

回答by Angel Fraga Parodi

you can make it with callback object and preventDefault function.

您可以使用回调对象和 preventDefault 函数来实现。

This sample is with 400 limit.

此样本限制为 400。

  function registerSummernote(element, placeholder, max, callbackMax) {
    $(element).summernote({
      toolbar: [
        ['style', ['bold', 'italic', 'underline', 'clear']]
      ],
      placeholder,
      callbacks: {
        onKeydown: function(e) {
          var t = e.currentTarget.innerText;
          if (t.length >= max) {
            //delete key
            if (e.keyCode != 8)
              e.preventDefault();
            // add other keys ...
          }
        },
        onKeyup: function(e) {
          var t = e.currentTarget.innerText;
          if (typeof callbackMax == 'function') {
            callbackMax(max - t.length);
          }
        },
        onPaste: function(e) {
          var t = e.currentTarget.innerText;
          var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
          e.preventDefault();
          var all = t + bufferText;
          document.execCommand('insertText', false, all.trim().substring(0, 400));
          if (typeof callbackMax == 'function') {
            callbackMax(max - t.length);
          }
        }
      }
    });
  }


$(function(){
  registerSummernote('.summernote', 'Leave a comment', 400, function(max) {
    $('#maxContentPost').text(max)
  });
});
    
<!-- include libraries(jQuery, bootstrap) -->
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>

<!-- include summernote css/js -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <div class="summernote"></div>
    </div>
    <div class="col-xs-12 text-right">
      <span id="maxContentPost"></span>
    </div>
  </div>
</div>

回答by Hokascha

Based on Angel Fraga Parodi's answer I added some more keyCodes that should always be allowed like delete, arrow keys or ctrl+x/ctrl+c. Also the code for pasting wasn't working (anymore). Here's an updated version:

根据 Angel Fraga Parodi 的回答,我添加了更多应该始终允许的 keyCode,例如删除、箭头键或 ctrl+x/ctrl+c。粘贴代码也不起作用(不再)。这是一个更新的版本:

<div class="summernote" ></div>
<h5 id="maxContentPost" style="text-align:right"></h5>
<script>
        $(document).ready(function () {
            $('.summernote').summernote({
                toolbar: [
                  ['style', ['bold', 'italic', 'underline', 'clear']]
                ],
                placeholder: 'Leave a comment ...',
                callbacks: {
                    onKeydown: function (e) { 
                        var t = e.currentTarget.innerText; 
                        if (t.trim().length >= 400) {
                            //delete keys, arrow keys, copy, cut, select all
                            if (e.keyCode != 8 && !(e.keyCode >=37 && e.keyCode <=40) && e.keyCode != 46 && !(e.keyCode == 88 && e.ctrlKey) && !(e.keyCode == 67 && e.ctrlKey) && !(e.keyCode == 65 && e.ctrlKey))
                            e.preventDefault(); 
                        } 
                    },
                    onKeyup: function (e) {
                        var t = e.currentTarget.innerText;
                        $('#maxContentPost').text(400 - t.trim().length);
                    },
                    onPaste: function (e) {
                        var t = e.currentTarget.innerText;
                        var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
                        e.preventDefault();
                        var maxPaste = bufferText.length;
                        if(t.length + bufferText.length > 400){
                            maxPaste = 400 - t.length;
                        }
                        if(maxPaste > 0){
                            document.execCommand('insertText', false, bufferText.substring(0, maxPaste));
                        }
                        $('#maxContentPost').text(400 - t.length);
                    }
                }
            });
        });
</script>

回答by Varsha

use the 'onKeydown' callback to check the current length of the editor's contents and possibly prevent further typing if that value is greater than or equal to the max length of your choice.

使用“onKeydown”回调来检查编辑器内容的当前长度,如果该值大于或等于您选择的最大长度,则可能会阻止进一步输入。

onKeydown: function(e) {
            if (e.keyCode == 8 /*and other buttons that should work even if MAX_LENGTH is reached*/) 
                return;
            if ($(".note-editable").text().length >= MAX_LENGTH){
                e.preventDefault();
                return;
            }    
},

回答by Fernando Shaiane Leoncio

I wrote this jquery solution based on the Summernote .note-editableclass.

我基于 Summernote.note-editable类编写了这个 jquery 解决方案。

//Contador de Caracteres para summernote
$(".note-editable").on("keypress", function(){
    var limiteCaracteres = 255;
    var caracteres = $(this).text();
    var totalCaracteres = caracteres.length;

    //Update value
    $("#total-caracteres").text(totalCaracteres);

    //Check and Limit Charaters
    if(totalCaracteres >= limiteCaracteres){
        return false;
    }
});

To display character count, just add a <span id="total-caracteres"></span>after <div class="summernote"></div>.

要显示字符数,只需<span id="total-caracteres"></span><div class="summernote"></div>.