gpt4 book ai didi

javascript - 在插入符号位置插入嵌套元素

转载 作者:行者123 更新时间:2023-12-03 08:51:52 26 4
gpt4 key购买 nike

我正在将 contenteditable div 与 range 结合使用,在 HTML 中的插入符位置插入、删除、更改、注释和格式化选项。 我已经使用范围函数 SplitAtcaret 实现了插入新段落:http://jsfiddle.net/timdown/rr9qs/2/ 。这运作良好。

现在我需要实现相同的插入新部分,就像部分中的段落概念一样。

部分例如:

输入 HTML:

<div class="section_level1" >
<h1>First Level section Heading</h1>
<p>Level First some text some text some paragraphs. </p>
<div class="section_level2" >
<h1>Second Level section Heading</h1>
<p>Second level some text <rangy position> insert new section (level 1) here </rangy posiiton > some text some paragraphs. </p>
<div class="section_level3" >
<h1>Third Level section Heading</h1>
<p>Third level some text dummy text dummy text.some paragraphs. </p>
</div>
</div>
</div>

需要输出 Html 为(在插入符位置(第二级内)插入新部分时。):

<div class="section_level1" >
<h1>First Level section Heading</h1>
<p>Level First some text some text some paragraphs. </p>
<div class="section_level2" >
<h1>Second Level section Heading</h1>
<p>Second level some text <p>
</div>
</div>
<div class="section_level1" >
<h1>Level 1 heading goes here </h1>
<p> Level 1 contents goes here. </p>
<div class="section_level2" >
<h1>dummy heading</h1>
<p>Second level some text <p>
<div class="section_level3" >
<h1>Third Level section Heading</h1>
<p>Third level some text dummy text dummy text.some paragraphs. </p>
</div>
</div>
</div>

最佳答案

您可以使用 Tim Down 的 splitParaAtCaret :

function splitParaAtCaret() {
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);
}
}
}

修改搜索包含元素的代码以搜索类名:

    while (p && (p.nodeType != 1 || p.className != "section_level1") ) {
p = p.parentNode;
}

关于javascript - 在插入符号位置插入嵌套元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645239/

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