2016-07-23 58 views
0

由于各种原因,我决定使用contenteditable DIV代替标准表单元素,但是我遇到了一个问题。使用jquery,我试图阻止div超过最大长度。光标在删除最后一个字符时返回contenteditable Div的起始点

代码工作得不错,但是当我剪辑最后一个字符时,光标会返回到字符串中的第一个字符。结果是,如果有人键入超过最大字符点,则字符串开始追加键入的新字符,并且一次截断已经存在一次键击的字符。

这是我使用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/

+0

你可以添加一个[jsFiddle](https://jsfiddle.net/)来复制问题吗? –

+0

https://jsfiddle.net/cLz7034v/14/ –

+0

您是否在发布之前搜索/尝试编码? [获取光标位置](http://stackoverflow.com/questions/4767848/get-caret-cursor-position-in-contenteditable-area-containing-html-content),[set cursor position](http:// stackoverflow .com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div) – Dekel

回答

1

不要改变用户输入。只是不允许输入更多的字符。

$('.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; 
}); 
+0

我也考虑过这一点,我更喜欢这种方法,但我担心会计所有通常使用的密钥。但是,如果我没有看到其他任何东西,我现在最喜欢这个答案。感谢您列举键码! –

+0

我决定接受这个答案,因为它的外观和作品最干净。我放入了一些代码来检测CTRL键,然后将a,x和c添加到允许的列表中,以便我可以选择,复制和剪切。如果我找到了我需要的其他键,我会添加它们。 –

相关问题