gpt4 book ai didi

javascript - Rangy (JS/jQuery) 拆分节点

转载 作者:数据小太阳 更新时间:2023-10-29 05:08:28 25 4
gpt4 key购买 nike

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

例如我有这个标记:

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

(这个管道代表位置/选择)

我想把它转换成:

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

维护选择。

有什么想法吗?

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

最佳答案

您可以通过创建一个从插入符号延伸到紧接段落之后的点的范围并使用它的 extractContents() 来做到这一点。方法。

现场演示: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);
}
}

关于javascript - Rangy (JS/jQuery) 拆分节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11111704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com