如何将所有选定的文本包装到span元素中?

rel*_*don 5 javascript dom selection

如何从一个元素中选择文本有很多问题得到解答。例如,从这个答案

function surroundSelection() {
    var span = document.createElement("span");
    span.style.fontWeight = "bold";
    span.style.color = "green";

    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我们如何对多个标签执行此操作呢?例如,如果这是标记

<p>Lorem ipsum dolor sit amet,</p>
<p>consectetur START HERE adipisicing elit.</p>
<p>Eaque et END HERE possimus at minima, illo?</p>
Run Code Online (Sandbox Code Playgroud)

如果用户选择第二段和第三段中的文本,如何将其包装在自己的单独 div 中

<p>Lorem ipsum dolor sit amet,</p>
<p>consectetur <span>adipisicing elit.</span></p>
<p><span>Eaque et</span> possimus at minima, illo?</p>
Run Code Online (Sandbox Code Playgroud)

我希望这个“破碎”的例子有帮助

小智 0

您可以使用window.getSelectionwindow.getSelection.toString()

我做了一个快速示例,在 h4 元素中显示所选文本。

function getSelectedText() {
    let selectedText = document.getElementById('selectedText');
    
    if (window.getSelection) {
        selectedText.innerHTML = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        selectedText.innerHTML = document.selection.createRange().text;
    }
 
}
Run Code Online (Sandbox Code Playgroud)
<p>Lorem ipsum dolor sit amet,</p>
<p>consectetur START HERE adipisicing elit.</p>
<p>Eaque et END HERE possimus at minima, illo?</p>
<input type="button" onclick="getSelectedText()" value="Get Selection">
<h4 id="selectedText"></h4>
Run Code Online (Sandbox Code Playgroud)

您还可以在Codepen上查看正在运行的代码。