2013-04-17 49 views
2

我有下面的代碼,一旦當前段落被刪除,重點放在前一段落。段落末尾的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/

+0

檢查此鏈接http://stackoverflow.com/questions/6003300/how-to -place-cursor-at-end-of-text-in-textarea-when-tabbed-into –

+0

看到這個http://jsfiddle.net/NHmmq/ – Anujith

回答

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)); 
    }; 
}); 
+0

是否有可能修改這個接受索引而不是總是回到最後?像'setEndOfContenteditable(prev.get(0),3)'就會將光標移動到段落中的位置3。 –

相關問題