如何锁定键盘以限制textarea中的字符数? [英] How can I lock the keyboard to limit the number of characters in a textarea?
问题描述
以下代码对于在textarea达到一定长度时在IE6和IE8中锁定键盘非常有用。当然,它在其他浏览器上不起作用,我无法找到一种方法将它变成一个可以跨浏览器工作的jQuery函数。是否可以在FireFox和Webkit浏览器中获得相同的行为?
The following code works great for locking the keyboard in IE6 and IE8 when a textarea reaches a certain length. Of course, it doesn't work on other browsers, and I can't figure out a way to turn it into a jQuery function that will work cross-browser. Is it possible to get the same behavior in FireFox and Webkit browsers?
function checkLength(fld, maxLength){
if(fld.value.length > maxLength-1){
event.returnValue = false;
}
}
<p><textarea name="third" id="third" onkeypress="checkLength(this, 10);">hello</textarea></p>
推荐答案
我要在这里插入我自己的博客 -
I'm going to plug my own blog here -
http://blog.jbstrickler.com/2010/11/textarea-size-limit-w-counter/
如果你想要一些非常简单的东西,你可以这样做 -
If you want something very simple, you could do -
<textarea onkeypress="return (this.value.length < 50);"></textarea>
其中50是您想要限制的字符数量。
Where 50 is how many characters you want to limit.
编辑:根据Jason的评论,我不想在这里给出错误的印象,即内联脚本是好的...
Per Jason's comment, I didn't want to give the wrong impression here that inline scripting is okay...
$('textarea').keypress(function() {
return $(this).val().length < 50;
});
这篇关于如何锁定键盘以限制textarea中的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!