簡體   English   中英

如何將所有選定的文本包裝到 span 元素中?

[英]How to wrap all selected text into span elements?

有很多問題回答了如何從一個元素到 select 文本。 例如, 從這個答案

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.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上查看正在運行的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM