在CSS :: selection中维护继承背景

时间:2019-01-08 20:12:35

标签: css selection background-color

根据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>&nbsp;
<p id="normal">This text maintains the standard highlight color, which I want to maintain.</p>
<br>
<button onclick="selectText('changed')">Select</button>&nbsp;
<p id="changed">When I try to change the foreground color of the selection, the background color is unset.</p>

0 个答案:

没有答案