简体   繁体   English

如何在具有 maxLength 属性的输入中获取所有粘贴的字符串?

[英]How to get all of the pasted string, in input which has a maxLength attribute?

I need to get all of the pasted string in input which has a maxLength attribute.我需要在具有 maxLength 属性的输入中获取所有粘贴的字符串。

But in 'onpaste' event there is no property to get all of the pasted string.但是在 'onpaste' 事件中没有属性可以获取所有粘贴的字符串。

For example, check below snippet with this string:例如,使用此字符串检查以下代码段:

"AAAAA-BBBBB-BBBBB-BBBBB-BBBBB" “AAAAA-BBBBB-BBBBB-BBBBB-BBBBB”

The output is: "AAAAA" output 是:“AAAAA”

But I need all of the string.但我需要所有的字符串。

 const onPasteFn = (e) => { setTimeout(() => document.getElementById("demo").innerHTML = e.target.value, 0) }
 <input type="text" maxLength="5" onpaste="onPasteFn(event)" /> <p id="demo"></p>

Consider using clipboardData from the event, where you can use getData() to grab the text that was pasted from the clipboard like so:考虑使用事件中的clipboardData ,您可以在其中使用getData()来获取从剪贴板粘贴的文本,如下所示:

 const onPasteFn = (e) => { document.getElementById("demo").textContent = (e.clipboardData || window.clipboardData).getData('text'); }
 <input type="text" maxLength="5" onpaste="onPasteFn(event)" /> <p id="demo"></p>

See example here from the docs.请参阅文档中示例。 Note that the fallback of || window.clipboardData请注意|| window.clipboardData的回退|| window.clipboardData is used for IE support. || window.clipboardData用于 IE 支持。

You can access clipboardData through function getData() , and print it instead of e.target.value() .您可以通过 function getData()访问clipboardData ,并打印它而不是e.target.value() If you store it in a temporary variable, like I did in my example, you are able to perform further elaboration on the pasted string.如果您将它存储在一个临时变量中,就像我在示例中所做的那样,您就可以对粘贴的字符串进行进一步的阐述。

It works for reasonably recent versions of browsers (for example FF 22+ ).它适用于相当新版本的浏览器(例如FF 22+ )。

 const onPasteFn = (e) => { var myData = e.clipboardData.getData("text/plain"); setTimeout(() => document.getElementById("demo").innerHTML = myData, 0) }
 <input type="text" maxLength="5" onpaste="onPasteFn(event)" /> <p id="demo"></p>

Set a higher maxLength if the pasted string is expected to be larger.如果粘贴的字符串预计会更大,请设置更高的maxLength Your sample input string has length 29. So here is modified code with maxLength=30 .您的示例输入字符串的长度为 29。所以这里是修改后的代码maxLength=30

 const onPasteFn = (e) => { setTimeout(() => document.getElementById("demo").innerHTML = e.target.value, 0) }
 <input type="text" maxLength="30" onpaste="onPasteFn(event)" /> <p id="demo"></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM