首页 > 解决方案 > 反转选择内的颜色

问题描述

我正在制作我的网站,但遇到了问题。

我正在尝试在文本选择中反转颜色。我试过这个,但它不起作用:

::selection {
    fiter: invert();
}

::selection {
  color: white;
  background-color: black;
}
.p1 {
    color: black;
    background-color: white;
}
.p2 {
    color: red;
    background-color: white;
}
.p3 {
    color: cyan;
    background-color: black;
}
<p class="p1">Paragraph 1</p>
<p class="p2">Paragraph 2</p>
<p class="p3">After select I want paragraph 2 to look like this:</p>

你能帮我吗?

标签: javascripthtmlcss

解决方案


我看不到如何在复杂的情况下执行此操作,其中选择包含几个可能单独设置颜色和背景颜色的 HTML 元素(当然,一些复杂的 HTML/CSS 解析必须能够做到这一点,但我不能)。

但是,我们可以相当简单地处理颜色和背景颜色在选择的父 div 中保持一致的简单情况。

在选择事件中,该片段读取父元素的计算样式,计算颜色和背景颜色的倒数,并将 CSS 变量设置为这些变量,这些变量在选择伪元素中被拾取和使用。

document.addEventListener('selectionchange', (e) => {
  function invert(color) {
    color = color.replace('rgb(', '');
    color = color.replace(')', '');
    color = color.replace('rgba(', '');
    let colors = color.split(',');
    let r = colors[0].replace(' ', '');
    let g = colors[1].replace(' ', '');
    let b = colors[2].replace(' ', '');
    let a = (colors.length > 3) ? colors[3].replace(' ', '') : 1;
    r = ~r & 255;
    g = ~g & 255;
    b = ~b & 255;
    return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + a + ')';
  }
  selection = window.getSelection();
  if (selection.anchorNode) {
    const parent = selection.anchorNode.parentElement;
    const style = window.getComputedStyle(parent);
    parent.style.setProperty('--color', invert(style.color));
    parent.style.setProperty('--background-color', invert(style.backgroundColor));
  }
});
.invertSelectionColors::selection {
  color: var(--color);
  background-color: var(--background-color);
}
<div class="invertSelectionColors" style="background-color: cyan;color:#000000;">
  here is some text originally background color cyan and color #000000
</div>
<div class="invertSelectionColors" style="background-color: rgba(255, 0, 0, 0.5);color:#0000ffff;">
  here is some text originally background color rgba(255, 0, 0, 0.5) and color #0000ffff
</div>


推荐阅读