限制可以在textarea中粘贴多少个字符 [英] limit how many characters can be pasted in textarea
本文介绍了限制可以在textarea中粘贴多少个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以检测到有多少字符被粘贴到HTML textarea中,并且如果超出限制则取消粘贴?
编辑:我正在尝试的这样做是为了防止用户粘贴大量的字符(~3百万),因为它会使一些浏览器崩溃。所以我想在浏览器锁定之前取消粘贴。我正在制作一个文档编辑器,用户可能会尝试这个。但他们可以根据自己的需要输入。
解决方案
您可以在jQuery上这样做:
$(document).ready(function(){
函数限制(obj,limit){
var text = $(obj).val();
var length = text.length;
if(length> limit){
$(obj).val(text.substr(0 ,limit));
} else {//提醒用户剩下的char。我在这里提醒,但是你可以做任何其他你喜欢的事情
alert(limit-length +characters remaining! );
$ b $('textarea')。keyup(function(){
limits($(this ),20);
})
})
查看演示此处。
Is it possible to detect how many characters are being pasted into a HTML textarea, and cancel the paste if beyond a limit?
Edit: what I am trying to do is prevent the user pasting a massive amount of characters (~3 million) because it crashes some browsers. So I want to cancel the paste before their browser locks up. I am making a document editor where users are likely to try this. But they can type as much as they want.
解决方案
you can do this on jQuery like this:
$(document).ready(function(){
function limits(obj, limit){
var text = $(obj).val();
var length = text.length;
if(length > limit){
$(obj).val(text.substr(0,limit));
} else { // alert the user of the remaining char. I do alert here, but you can do any other thing you like
alert(limit -length+ " characters remaining!");
}
}
$('textarea').keyup(function(){
limits($(this), 20);
})
})
view a demo here.
这篇关于限制可以在textarea中粘贴多少个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文