javascript - 反转选择内的颜色
问题描述
我正在制作我的网站,但遇到了问题。
我正在尝试在文本选择中反转颜色。我试过这个,但它不起作用:
::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>
你能帮我吗?
解决方案
我看不到如何在复杂的情况下执行此操作,其中选择包含几个可能单独设置颜色和背景颜色的 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>
推荐阅读
- sql-server - 将数据从 Azure 流分析插入 Azure SQL 数据库表时出现“OutputDataConversionError.TypeConversionError”
- django - 在生产中的 Django 中找不到 Favicon
- python - ValueError:在 plt.subplots() 中绘制 ax[i].scatter 时 x 和 y 的大小必须相同
- java - 如何通过鼠标拖动手动调整 JavaFX 中的窗格/矩形的大小?
- php - 如何在 woocommerce 上的特定时间段(例如 7 天)我的帐户 > 我的订单后按钮不可见(隐藏)?
- android - Android - 具有自定义字符串数据的 NumberPicker 显示错误值?
- ios - SWIFT中有两个条件的条件问题
- python - 在 Ansible 中使用 JINJA2 从 JSON 中提取带有条件的嵌套 dict 值
- python - 如何克服电子邮件标题中的 988 字符限制?
- python - 当我逐个像素地去时,Pygame 没有画任何东西