根据this answer,网站选择,背景颜色取决于操作系统/浏览器的组合。我想更改:: selection的前景色,但不更改背景;但是,更改前者似乎会使后者变得不可见。
//https://stackoverflow.com/questions/985272/selecting-text-in-an-element-akin-to-highlighting-with-your-mouse
function selectText(node) {
node = document.getElementById(node);
if (document.body.createTextRange) {
const range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
} else if (window.getSelection) {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
}
}
#changed::selection {
color: red;
}
button,
p {
display: inline;
}
<button onclick="selectText('normal')">Select</button>
<p id="normal">This text maintains the standard highlight color, which I want to maintain.</p>
<br>
<button onclick="selectText('changed')">Select</button>
<p id="changed">When I try to change the foreground color of the selection, the background color is unset.</p>