Set Cursor position after nested contentEditable

99封情书 提交于 2019-12-05 05:47:43
Edmund Moshammer

An update to the previous answer. http://jsfiddle.net/GLzKy/4/

placeCaretAtEnd($(this).parent().nextAll('.field').children('value'));

UPDATE

Updated answer with correct answer in comments

For moving directly after the current field, you might want to use range.setStartAfter and range.setEndAfter: http://jsfiddle.net/GLzKy/5

Selvakumar Arumugam

I am assuming that you want to go to this next section. To make it clear, I added a text "Here!" in a demo to show you that it does goes to the end.

In the below demo, press Enter key from the .field .value to go to the end.

DEMO: http://jsfiddle.net/GLzKy/1/

Below is the function from https://stackoverflow.com/a/4238971/297641 which actually does all the work.

$('.field .value').keydown(function (e) {
    if (e.which == 13) { //Enter Key
        e.preventDefault();            
        placeCaretAtEnd($(this).closest('.parent')[0]);
    }
});

/**
  This below function is from https://stackoverflow.com/a/4238971/297641
  All credits goes to the original author.
*/
function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

Tested in FF, IE8 and Chrome

Reference: https://stackoverflow.com/a/4238971/297641

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!