有很多问题回答了如何从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>
您可以使用window.getSelection和window.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处查看运行中的代码。