有一個小故障:第一個「酷」總是得到光標,因爲你通過「id」得到它。爲了避免這個問題,我在追加它之前創建了<p>cool</p>
元素,然後使用它來定位新的光標位置。
$(document).on('keypress', 'div[contenteditable="true"]', function(event) {
if (event.which == 13) { // enter key
event.preventDefault();
//insert the paragraph after this element.
var innerDiv = $("<p>cool</p>")
var sel = window.getSelection()
$(sel.anchorNode.parentNode).after(innerDiv);
//set cursor at new position
sel.collapse(innerDiv[0].firstChild, innerDiv.text().length);
}
});
JSFiddle
和無JQ版本:
document.querySelector('div[contenteditable="true"]').addEventListener('keypress', function(event) {
if (event.which == 13) { // enter key
event.preventDefault();
//insert the paragraph after this element.
var innerDiv = document.createElement('p')
innerDiv.innerHTML = 'cool'
var sel = window.getSelection()
var selElem = sel.anchorNode.parentNode
selElem.parentNode.insertBefore(innerDiv, selElem.nextSibling)
//set cursor at new position
sel.collapse(innerDiv.firstChild, innerDiv.textContent.length);
}
});
JSFiddle no-jQ