Rangy (JS/jQuery) split node

后端 未结 1 1142
死守一世寂寞
死守一世寂寞 2020-12-10 07:44

How would I split a node/element at a position (selection).

Example I have this markup:

This is a te|st, you li

相关标签:
1条回答
  • 2020-12-10 07:51

    You could do this by creating a range that extends from the caret to the point immediately after the paragraph and using its extractContents() method.

    Live demo: http://jsfiddle.net/timdown/rr9qs/2/

    Code:

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题