gpt4 book ai didi

javascript - 删除最后一个字符时光标返回到 contenteditable Div 的开头

转载 作者:行者123 更新时间:2023-12-03 06:28:14 24 4
gpt4 key购买 nike

出于各种原因,我决定使用 contenteditable DIV 而不是标准表单元素,但我遇到了问题。使用 Jquery,我试图防止 div 超过最大长度。

代码运行得很好,但是当我剪辑最后一个字符时,光标返回到字符串中的第一个字符。结果是,如果有人输入的内容超过了最大字符点,字符串就会开始追加输入的新字符,并一次一次击键一次 chop 已经存在的字符。

这是我正在使用的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;
});

关于javascript - 删除最后一个字符时光标返回到 contenteditable Div 的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38546383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com