由於各種原因,我決定使用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/
你可以添加一個[jsFiddle](https://jsfiddle.net/)來複制問題嗎? –
https://jsfiddle.net/cLz7034v/14/ –
您是否在發佈之前搜索/嘗試編碼? [獲取光標位置](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