jQuery focus()在段落末尾而不是开始

时间:2013-04-17 06:11:48

标签: javascript jquery

删除当前段落后,我有以下代码,重点关注上一段。

$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $(this).after('<p contenteditable = "true">New Paragraph</p>');
        $(this).next('p').focus();
    } else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
        e.preventDefault();
        var prev = $(this).prev('p');
        $(this).remove();
        prev.focus();
    };
});

但是它始终将光标移动到段落的开头。是否可以将光标移动到末尾?

http://jsfiddle.net/UU4Cg/6/

1 个答案:

答案 0 :(得分:1)

从这个精美的堆栈答案中获取功能,这似乎对我有用:How to move cursor to end of contenteditable entity

function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}

$(document).on('keyup', 'p[contenteditable="true"]', function(e) {
    if(e.which == 13) {
        e.preventDefault();
        $(this).after('<p contenteditable = "true">New Paragraph</p>');
        $(this).next('p').focus();
    } else if((e.which == 8 || e.which == 46) && $(this).text() == "") {
        e.preventDefault();
        var prev = $(this).prev('p');
        $(this).remove();
        prev.focus();
        setEndOfContenteditable(prev.get(0));
    };
});