如何在某个位置(选择)拆分节点/元素.
示例我有这个标记:
<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); } }