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

问题描述 投票:4回答:1

有很多问题回答了如何从one元素中选择文本。例如,from this answer

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);
        }
    }
}

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

<p>Lorem ipsum dolor sit amet,</p>
<p>consectetur START HERE adipisicing elit.</p>
<p>Eaque et END HERE possimus at minima, illo?</p>

如果用户从第二段和第三段中选择文本,如何将其包装在自己的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>

希望this "broken" example有帮助

javascript dom selection
1个回答
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;
    }
 
}
<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>

您还可以在Codepen处查看运行中的代码。

© www.soinside.com 2019 - 2024. All rights reserved.