我有这个小提琴: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>
标签,就像在一个所见即所得的编辑器中一样。有什么建议吗?
答案 0 :(得分:1)
喜欢这个?
$('p').on('keypress', function (e) {
if (e.keyCode === 13) {
e.preventDefault();
$(this).after('</p><p>');
}
});
答案 1 :(得分:1)
您可以使用新内容生成新的<p>
,并将其附加(或添加)到您的.content
容器中,此处为fiddle。
查看强>
<div class="content"><p class="new-content" contenteditable="true">Click</p></div>
<强> JS 强>
$(document).on("keypress", ".content", function (e) {
if (e.keyCode === 13) {
e.preventDefault();
var content = $("p.new-content").text();
$("<p>" + content + "</p>").insertBefore("p.new-content");
$("p.new-content").text("");
}
});
$(document).on("click", "p", function (e) {
$("p.new-content").removeClass("new-content").attr("contenteditable",false);
$(this).addClass("new-content").attr("contenteditable",true).focus();
});