我想用类似于色调旋转动画的方式为 ::selection
背景颜色设置动画。由于 ::selection
背景属性只能包含颜色或变量,我假设包含颜色的 ::root
变量应该以某种方式进行动画处理,而我不知道如何为没有类的东西设置动画.
也许 JS 有一个简单的解决方案,但我现在可能忽略了。
Vanilla JS 解决方案首选
答案 0 :(得分:1)
可以肯定这是不可能的。 ::selection
伪代码不接受 animation-*
属性 (see MDN)
只有某些 CSS 属性可以与 ::selection 一起使用:
color
background-color
cursor
caret-color
outline
及其常用工具text-decoration
及其相关属性text-emphasis-color
text-shadow
这让我觉得这是不可能的。我们可以使用 ::after
等其他伪代码来实现,但是每当我选择文本时,它的背景颜色都不会改变。
.something {
background-color: blue;
}
.something::selection {
color: white;
animation-duration: 3s;
animation-name: colorize;
animation-iteration-count: infinite;
animation-direction: alternate;
}
.something::after {
content: "after";
display: inline-block;
width: 50px;
height: 50px;
animation-duration: 3s;
animation-name: colorize;
animation-iteration-count: infinite;
animation-direction: alternate;
}
@keyframes colorize {
from {
background-color: green;
}
to {
background-color: red;
}
}
<span class="something">Hello</span>
即使尝试不断更新 CSS custom property 并“手动”为其设置动画似乎也不起作用,因为选择属性在突出显示时不会更新。例如,您可以选择“Hello World!”文本,您应该在每次突出显示时看到红色值发生变化,但 突出显示时不会发生变化。
const thing = document.getElementById("thing");
let r = 0;
const loop = () => {
thing.style.setProperty("--color", `rgb(${r}, 0, 0)`);
r++;
if (r > 255) {
r = 0;
}
requestAnimationFrame(loop);
};
requestAnimationFrame(loop);
:root {
--color: red;
}
#thing::selection {
background-color: var(--color, black);
}
<div id="thing">Hello world!</div>
答案 1 :(得分:0)
这现在在 chrome 和 firefox 中有效,但在 safari 中无效:
let r = 0;
const loop = () => {
var html = document.getElementsByTagName("html")[0];
html.style.setProperty("--changing", `hsla(${r}, 50%, 50%, 0.999)`);
r++;
requestAnimationFrame(loop);
};
requestAnimationFrame(loop);