admin管理员组文章数量:1401592
How would I split a node/element at a position (selection).
Example I have this markup:
<p>This is <a href="">a te|st</a>, you like?</p>
(this pipe represents the position/selection)
I want to convert it to:
<p>This is <a href="">a te</a></p>|<p><a href="">st</a>, you like?</p>
Maintaining the selection.
Any ideas?
I and using the Rangy library, and also jQuery, but can use raw JS if applicable.
How would I split a node/element at a position (selection).
Example I have this markup:
<p>This is <a href="">a te|st</a>, you like?</p>
(this pipe represents the position/selection)
I want to convert it to:
<p>This is <a href="">a te</a></p>|<p><a href="">st</a>, you like?</p>
Maintaining the selection.
Any ideas?
I and using the Rangy library, and also jQuery, but can use raw JS if applicable.
Share Improve this question asked Jun 20, 2012 at 1:30 PetahPetah 46.1k30 gold badges160 silver badges215 bronze badges1 Answer
Reset to default 10You 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/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.monAncestorContainer;
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);
}
}
本文标签: javascriptRangy (JSjQuery) split nodeStack Overflow
版权声明:本文标题:javascript - Rangy (JSjQuery) split node - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744260472a2597690.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论