Description
CDN Search
75CDN jsDelivr
<!DOCTYPE html>
<html>

<head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta charset="utf-8" />
	<title>NetnrRun</title>
</head>

<body>
	<p>对选中内容 复制 、 高亮</p>
	<p>该示例只是简单的演示,只支持单节点选中,如果跨节点选择需要更复杂的逻辑处理</p>
	<p>控制已经输出选中内容,复制到剪贴板的功能就相对简单了,可以调用一些插件来实现复制内容</p>
	<p>还有一些 BUG ,选中高亮和不高亮的内容会出问题,因为高亮和不高亮跨节点了</p>
	<p>2020-01-15 调整选中高亮为添加样式实现,可跨节点选中,也能正常得到选中的内容</p>
</body>

</html>
document.onmouseup = function () {
    var gs = document.getSelection();
    var txt = gs.toString();
    console.log(txt);
    if (txt != "" && gs.anchorNode == gs.focusNode) {
        var elem = gs.anchorNode.parentNode;
        var nitxt = elem.innerText, newtxt;
        if (nitxt.indexOf(txt) == nitxt.lastIndexOf(txt)) {
            // newtxt = nitxt.replace(txt, '<b style="background-color:orange;color:white">' + txt + '</b>');
        } else {
            var nis = Math.min(gs.baseOffset, gs.focusOffset);
            var nie = Math.max(gs.baseOffset, gs.focusOffset);
            // newtxt = nitxt.substr(0, nis) + '<b style="background-color:orange;color:white">' + nitxt.substring(nis, nie) + '</b>' + nitxt.substr(nie);
        }
        // elem.innerHTML = newtxt;
    }
}
p{
    float: left;
    margin: 1rem;
    padding: 1rem;
    border: 1px solid green;
}

/*选中高亮*/
p::selection{
    color:white;
    font-weight: 600;
    background-color:orange;
}