How to simulate JS ranges / selections using div as background?

I need to imitate ranges / selections (those that highlight content on a website, and when you click for ex CTRL + Cyou copy the content) with divs as the background. Most likely, "highlight divs" will beposition:absolute;

<div id="highlight">
   <!-- The highlightor divs would go here -->
</div>
<div id="edit">
   <!-- The divs to be highlighted (that have text) would go here -->
</div>

Edit: features like copying are needed.

PS: If you are wondering why, refer to this question . I created a new question because I felt that the old answer was quite a lot, and this one was very different from that.

+3
source share
1 answer

, , . , , , . , . , , , "ctrl + c", .

, , , , . Sniff "ctrl + a" ( ). , ... , . , , .

window.onload = init;
function init()
{
    document.getElementById("hidden").value = "";
    document.body.ondblclick = interceptSelection;
    document.body.onmouseup = interceptSelection;
}
function interceptSelection(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    var hidden = document.getElementById("hidden");
    if (target == hidden) return;
    var range, text;
    if (window.getSelection)
    {
        var sel = getSelection();
        if (sel.rangeCount == 0) return;
        range = getSelection().getRangeAt(0);
    }
    else if (document.selection && document.selection.createRange)
    {
        range = document.selection.createRange();
    }
    text = "text" in range ? range.text : range.toString();
    if (text)
    {
        if (range.surroundContents)
        {
            var span = document.createElement("span");
            span.className = "selection";
            range.surroundContents(span);
        }
        else if (range.pasteHTML)
        {
            range.pasteHTML("<span class=\"selection\">" + text + "</span>")
        }
        hidden.value += text;
    }
    hidden.select();
}

css, , :

#hidden
{
    position: fixed;
    top: -100%;
}
.selection
{
    background-color: Highlight;
    color: HighlightText;
}
0

Source: https://habr.com/ru/post/1787561/