删除最后一个字符时,光标 returns 到 contenteditable Div 的开头
Cursor returns to start of contenteditable Div when removing last character
出于各种原因我决定使用contenteditable DIV 代替标准表单元素,但是我运行 遇到了问题。使用 Jquery,我试图防止 div 超过最大长度。
代码运行良好,但是当我剪辑最后一个字符时,光标 returns 到字符串中的第一个字符。结果是,如果有人键入超过最大字符点,字符串将开始追加键入的新字符并截断已经存在的字符,一次一个键。
这是我正在使用的jquery:
$('.textarea_text').on('keyup',function() {
var remaining = $(this).data('max') - $(this).html().length;
if (remaining <0)
{
$(this).html($(this).html().slice(0,-1)); // Remove the last character
remaining=0;
}
$(this).closest('.textarea_area').find('.textarea_counter').html("("+remaining+" characters remaining)");
});
JSfiddle:https://jsfiddle.net/cLz7034v/14/
不要更改用户输入。只是不允许输入更多的字符。
$('.textarea_text').on('keydown',function(e) {//keydown instead of keyup
var remaining = $(this).data('max') - $(this).html().length;
$(this).closest('.textarea_area').find('.textarea_counter').html("("+remaining+" characters remaining)");
//console.log(e.which);
var allowedKeys=[8,35,36,37,38,39,40,46]; //arrows, home, end, del, backspace
if (remaining <=0 && allowedKeys.indexOf(e.which) == -1)
return false;
});
出于各种原因我决定使用contenteditable DIV 代替标准表单元素,但是我运行 遇到了问题。使用 Jquery,我试图防止 div 超过最大长度。
代码运行良好,但是当我剪辑最后一个字符时,光标 returns 到字符串中的第一个字符。结果是,如果有人键入超过最大字符点,字符串将开始追加键入的新字符并截断已经存在的字符,一次一个键。
这是我正在使用的jquery:
$('.textarea_text').on('keyup',function() {
var remaining = $(this).data('max') - $(this).html().length;
if (remaining <0)
{
$(this).html($(this).html().slice(0,-1)); // Remove the last character
remaining=0;
}
$(this).closest('.textarea_area').find('.textarea_counter').html("("+remaining+" characters remaining)");
});
JSfiddle:https://jsfiddle.net/cLz7034v/14/
不要更改用户输入。只是不允许输入更多的字符。
$('.textarea_text').on('keydown',function(e) {//keydown instead of keyup
var remaining = $(this).data('max') - $(this).html().length;
$(this).closest('.textarea_area').find('.textarea_counter').html("("+remaining+" characters remaining)");
//console.log(e.which);
var allowedKeys=[8,35,36,37,38,39,40,46]; //arrows, home, end, del, backspace
if (remaining <=0 && allowedKeys.indexOf(e.which) == -1)
return false;
});