输入密钥以创建新段落

时间:2013-11-06 01:26:21

标签: javascript jquery

我有这个小提琴: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>标签,就像在一个所见即所得的编辑器中一样。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

喜欢这个?

$('p').on('keypress', function (e) {
    if (e.keyCode === 13) {
        e.preventDefault();
        $(this).after('</p><p>');
    }
});

做了一个小提琴:http://jsfiddle.net/filever10/5QXqH/

答案 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();
});