如何在编辑器中粘贴文本时只显示几个字符?

时间:2018-04-27 04:30:46

标签: javascript

尝试粘贴字符,如果超过50个字符仅显示前50个字符。谁能告诉我我失踪了什么?

这是我的代码:LIVE DEMO

CKEDITOR.instances.foo.on('paste',function(event){

    alert('paste');
    var deleteKey = 46;
    var backspaceKey = 8;
    var keyCode = event.data.keyCode;
    if (keyCode === deleteKey || keyCode === backspaceKey)
        return true;
    else
    {
        var textLimit = 50;
        var str = CKEDITOR.instances.foo.getData();
        if (str.length >= textLimit)
        // Need to add code here to only show the first 50 characters
            return false;
    }
});

3 个答案:

答案 0 :(得分:3)

您可以使用WORDCOUNT的{​​{1}}插件,您可以找到示例

https://ckeditor.com/cke4/addon/wordcount

答案 1 :(得分:0)

the document show about paste event.

https://docs.ckeditor.com/ckeditor4/latest/guide/dev_clipboard.html#the-paste-event

you could use event.data.dataValue to get the paste content.
code is here:

http://jsfiddle.net/2vzkLb8L/2/

CKEDITOR.instances.foo.on('paste',function(event){
    var pasteContent = event.data.dataValue;
    var str = CKEDITOR.instances.foo.getData();
    var textLimit = 50;
    var newcontent = pasteContent + str; 
    CKEDITOR.instances.foo.setData(newcontent.slice(0,50))
});  

答案 2 :(得分:0)

您可以使用此event.data.dataValue从CKEditor获取和设置数据

CKEDITOR.instances.foo.on('paste',function(event){
  var textLimit = 50;
  var str = $(event.data.dataValue).text();

   if (str.length >= textLimit) {
    event.data.dataValue = str.substr(0 , textLimit);
  } 
});

http://jsfiddle.net/2ftroyuv/7/