问题描述
我在我的网络应用程序中使用了contenteditable div元素,我正在尝试提出一个限制区域中允许的字符数量的解决方案,一旦达到限制,尝试输入字符就什么都不做。这是我到目前为止:
I am using contenteditable div elements in my web application and I am trying to come up with a solution to limit the amount of characters allowed in the area, and once the limit is hit, attempting to enter characters simply does nothing. This is what I have so far:
var content_id = 'editable_div';
//binding keyup/down events on the contenteditable div
$('#'+content_id).keyup(function(){ check_charcount(content_id, max); });
$('#'+content_id).keydown(function(){ check_charcount(content_id, max); });
function check_charcount(content_id, max)
{
if($('#'+content_id).text().length > max)
{
$('#'+content_id).text($('#'+content_id).text().substring(0, max));
}
}
此DOES将字符数限制为指定的数字通过'max',但是一旦区域的文本由jquery .text()函数设置,光标就会将自身重置为区域的开头。因此,如果用户继续键入,则新输入的字符将插入文本的开头,并且将删除文本的最后一个字符。所以,我只需要一些方法将光标保持在可信区域文本的末尾。
This DOES limit the number of characters to the number specified by 'max', however once the area's text is set by the jquery .text() function the cursor resets itself to the beginning of the area. So if the user keeps on typing, the newly entered characters will be inserted at the beginning of the text and the last character of the text will be removed. So really, I just need some way to keep the cursor at the end of the contenteditable area's text.
推荐答案
如何将事件
对象传递给您的函数并调用 e.preventDefault()
如果达到最大值?
How about passing in the event
object to your function and calling e.preventDefault()
if the max is reached?
var content_id = 'editable_div';
max = 10;
//binding keyup/down events on the contenteditable div
$('#'+content_id).keyup(function(e){ check_charcount(content_id, max, e); });
$('#'+content_id).keydown(function(e){ check_charcount(content_id, max, e); });
function check_charcount(content_id, max, e)
{
if(e.which != 8 && $('#'+content_id).text().length > max)
{
// $('#'+content_id).text($('#'+content_id).text().substring(0, max));
e.preventDefault();
}
}
尽管如此,您可能需要多做一点允许用户执行删除等操作。
Although, you may need to do a little more to allow the user to do things like 'delete'.
编辑:
添加了对删除键的支持。
Added support for 'delete' key.
编辑2 :
此外,您可能可以摆脱 keyup
处理程序。 keydown
应该足够了。
Also, you could probably get rid of the keyup
handler. keydown
should be enough.
这篇关于限制ContentEditable div中的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!