粘贴时javascript onkeypress限制字符

时间:2019-05-13 13:15:26

标签: javascript html textarea aurelia maxlength

我在奥雷利亚(Aurelia)有一个keydown.trigger的文本区域:

<textarea name="description" keydown.trigger="handleKeypress($event, $event.target.value)" 
value.bind="desc" ></textarea>

在.js文件中,我有以下代码:

handleKeypress(event,newValue) { 
  let max = 3413;
  let valueSize = new Blob([newValue]).size; 
  if (event.charCode >= 48 && event.charCode <= 57 || event.key === "Backspace") {
    return true;
  }
  else {
    event.onpaste = function(e){
        e.clipboardData.getData('text/plain').slice(0, max);
};
    if (valueSize>= max) {return false;} 
  }
  return true;
}

因此,在textarea中,该字符的字符数不得超过3413个字节,因为在DB中,字节数是有限制的,因此在这里不能使用简单的maxlength。

此代码可以正常工作,不允许输入更多字符。它也不允许使用CTRL + V粘贴文本,只有在达到限制时才可以粘贴。

问题是,当尚未达到限制并且有人通过CTRL + V或右键单击粘贴长文本时-粘贴。然后粘贴内容,并且超出文本区域的限制。

我想实现textarea显示的字符数不超过限制

更新:我还尝试通过e.clipboardData.getData('text/plain').slice(0, max);

从另一个线程使用上述解决方案

但是对于我来说,这没有任何作用。

1 个答案:

答案 0 :(得分:3)

使用maxlength有什么问题?

我尝试过,它对我有用:

<template>
     <textarea name="description" maxlength.bind="max" value.bind="desc"></textarea>
</template>

在视图模型中:

export class Test {
  max = 3;
}

我在codeandbox中对此进行了测试,并且工作正常。参见https://codesandbox.io/embed/4zy4k5r3k7

相关问题