我有这个小提琴:http: //jsfiddle.net/2mw4c/1/
$(document).on("keypress", ".content", function (e) {
if (e.keyCode === 13) {
e.preventDefault();
pasteHtmlAtCaret('</p><p>');
}
});
function pasteHtmlAtCaret(html){
var sel, range;
if(window.getSelection){
// IE9 and non-IE
sel = window.getSelection();
if(sel.getRangeAt && sel.rangeCount){
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while((node = el.firstChild)){
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if(lastNode){
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
}else if(document.selection && document.selection.type != "Control"){
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
我不确定当有人按下回车键时我将如何完成任务,它将跳出当前<p>
标签并开始一个新<p>
标签,就像在所见即所得的编辑器中一样。有什么建议么?