在插入位置插入嵌套元素

时间:2015-09-18 06:29:21

标签: javascript jquery html dom rangy

我正在使用一个contenteditable div结合rangy来插入,删除,更改,评论和格式化HTML中的插入位置选项。  我已经实现了使用rangy函数SplitAtcaret插入一个新段落:http://jsfiddle.net/timdown/rr9qs/2/。这很好用。

现在我需要在部分中实现相同的插入新部分,如段落概念。

部分例如:

输入HTML:

<div class="section_level1" >
    <h1>First Level section Heading</h1>
    <p>Level First some text some text some paragraphs. </p>
    <div class="section_level2" >
        <h1>Second Level section Heading</h1>
        <p>Second level some text <rangy position> insert new section (level 1)  here  </rangy posiiton > some text some paragraphs. </p>
        <div class="section_level3" >
            <h1>Third Level section Heading</h1>
            <p>Third level some text dummy text dummy text.some paragraphs. </p>
        </div>
    </div>
</div>

需要输出Html(在插入位置(在第二级内)插入新部分时。):

<div class="section_level1" >
    <h1>First Level section Heading</h1>
    <p>Level First some text some text some paragraphs. </p>
    <div class="section_level2" >
        <h1>Second Level section Heading</h1>
        <p>Second level some text <p>
    </div>
</div>
<div class="section_level1" >  
    <h1>Level 1 heading goes here </h1>
    <p> Level 1 contents goes here. </p>
    <div class="section_level2" >
        <h1>dummy heading</h1>
        <p>Second level some text <p>
        <div class="section_level3" >
            <h1>Third Level section Heading</h1>
            <p>Third level some text dummy text dummy text.some paragraphs. </p>
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

你可以使用Tim Down的splitParaAtCaret

function splitParaAtCaret() {
    var sel = rangy.getSelection();
    if (sel.rangeCount > 0) {
        // Create a copy of the selection range to work with
        var range = sel.getRangeAt(0).cloneRange();

        // Get the containing paragraph
        var p = range.commonAncestorContainer;
        while (p && (p.nodeType != 1 || p.tagName != "P") ) {
            p = p.parentNode;
        }

        if (p) {
            // Place the end of the range after the paragraph
            range.setEndAfter(p);

            // Extract the contents of the paragraph after the caret into a fragment
            var contentAfterRangeStart = range.extractContents();

            // Collapse the range immediately after the paragraph
            range.collapseAfter(p);

            // Insert the content
            range.insertNode(contentAfterRangeStart);

            // Move the caret to the insertion point
            range.collapseAfter(p);
            sel.setSingleRange(range);
        }
    }
}

修改搜索包含元素的代码以搜索类名:

    while (p && (p.nodeType != 1 || p.className != "section_level1") ) {
        p = p.parentNode;
    }