Rangy(JS / jQuery)拆分节点 [英] Rangy (JS/jQuery) split node

查看:161
本文介绍了Rangy(JS / jQuery)拆分节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一个位置(选择)拆分节点/元素。

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

示例我有这个标记:

<p>This is <a href="">a te|st</a>, you like?</p>

(此管道代表仓位/选择)

(this pipe represents the position/selection)

我想将其转换为:

<p>This is <a href="">a te</a></p>|<p><a href="">st</a>, you like?</p>

维持选择。

任何想法?

我使用Rangy库和jQuery,但如果适用,可以使用原始JS。

I and using the Rangy library, and also jQuery, but can use raw JS if applicable.

推荐答案

您可以通过创建从插入符号延伸到段落后面的点并使用其 extractContents() method。

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.

现场演示: http://jsfiddle.net / timdown / rr9qs / 2 /

代码:

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);
    }
}

这篇关于Rangy(JS / jQuery)拆分节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆