Bryan Allo發佈的答案沒有考慮到您需要將光標放在div的末尾。否則,在每次替換操作時,用戶將不得不按下CTRL-End。
這是我提出的解決方案,同時在行動,在http://jsfiddle.net/82dS6/可以看出:
function setEndOfContenteditable(contentEditableElement){
// Taken from http://stackoverflow.com/a/3866442/1601088
var range,selection;
if(document.createRange){//Firefox, Chrome, Opera, Safari, IE 9+
range = document.createRange();
range.selectNodeContents(contentEditableElement);
range.collapse(false);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
else if(document.selection){//IE 8 and lower
range = document.body.createTextRange();
range.moveToElementText(contentEditableElement);
range.collapse(false);
range.select();
}
}
function replaceDivWithP(el){
$(el).find('div').each(function(){
$(this).replaceWith($('<p>' + $(this).html() + '</p>'));
});
}
$(function(){
$(".text").simpleEdit();
});
$('.textarea').bind('keyup', function(){
replaceDivWithP(this);
setEndOfContenteditable(this);
});
這將張貼您知道的一個問題。如果你用段落標籤而不是div來替換你的容器元素,那麼連續的列表將是段落的子元素,這是無效的html。 –