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

标签 javascript jquery contenteditable

出于各种原因,我决定使用 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/

相关文章:

javascript - 在特定屏幕分辨率下隐藏标签

javascript - 在 javascript/jquery 中传递可选参数

javascript - onClick() -> Loading/onSuccess -> addClass 或 removeClass (JS)

vue.js - VueJS 2 从父方法更新组件中的 contenteditable

javascript execCommand ('delete' ) 不删除 chrome 中的所有选择 div

javascript - 如何在 contenteditable div 中创建一个段落?

javascript - #import 如何在 iOS 的 UI 自动化中工作?

javascript - 如何在表单元素中将按钮标记为事件 onclick

Javascript解构并分配给新对象

javascript - 将 jQuery post 发送到 MVC Controller 时出现 404 错误