2016-07-23 49 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添加到允許的列表中,以便我可以選擇,複製和剪切。如果我找到了我需要的其他鍵,我會添加它們。 –

相關問題