gpt4 book ai didi

javascript - 序列化 html : placing span elements around selected text while preserving the HTML structure

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

我正在尝试制作一个文本荧光笔,教师可以在其中选择一系列文本,以便学生可以跟随。文本采用 HTML 格式,因此有 <p> , <b> , <em>等等...元素。

为了突出显示文本范围,我将范围包装在 span 元素中。

问题:

https://jsfiddle.net/7fedkobr/1/

这是一个带有一些 HTML 标记的句子:

<p>The <b>quick</b> brown fox jumps over the <em>lazy</em> dog</p>

当我选择“The”之类的单词时,它会被包裹在 <span> 中。 ,繁荣,没问题。

当我尝试选择任何 html 标签时,就会出现问题...例如,如果我选择整个句子,那么我就会丢失所有标记。

我在寻找什么。

一种序列化跨度的方法,使它们位于 html 元素之间并包裹所有文本。

使用前面的示例:如果我选择上面的整个句子,那么我将得到以下输出:

<p><span>The </span><b><span>quick</span></b><span> brown fox jumps over the </span><em><span>lazy</span></em><span> dog</span></p>

问:

有这种序列化的方法吗?我在 jQuery 文档中找不到任何内容,我问过的几个人都被难住了。

最佳答案

关键是使用range.extractContents() 。该文档说明了满足您需求的最重要部分:

Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid.

document.getElementById('test').addEventListener('mouseup', function() {
var range = window.getSelection().getRangeAt(0),
span = document.createElement('span');

span.className = 'highlight';
span.appendChild(range.extractContents());
range.insertNode(span);
});
.highlight { background-color: yellow; }
<div id="test">
Select any part of <b>this sentence and</b> and then move the mouse to a new location.
</div>

您可以在下图中看到,选择结果的 HTML 完全符合您的要求:

DOM representation of selection.

关于javascript - 序列化 html : placing span elements around selected text while preserving the HTML structure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42656501/

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