通过javascript更改文本颜色,而不更改其:悬停颜色



我有这个css:

.overlay-left-a {
color:red;
}
.overlay-left-a:hover {
color:black;
}

这个javascript:

let gr1 = document.getElementsByClassName("overlay-left-a");
for (let i = 0; i < gr1.length; i++) {
gr1[i].style.color = blue;
}

但我希望我的javascript不要改变":悬停"的颜色。

什么是最好的方法?

在您的情况下,您可以这样做:在不覆盖悬停颜色的情况下更改CSS变量。主要部分是这个CSS:

:root {
--color: red;
}
.overlay-left-a {
color: var(--color);
}

然后你可以像这样更改:root上的颜色值:

document.documentElement.style.setProperty("--color", "blue");
//                                    Or whatever −−−−^^^^^^

实例:

document.querySelector("input[type=button]").addEventListener("click", (e) => {
// Get the color
const color = document.getElementById("txt-color").value.trim();
// Apply it
document.documentElement.style.setProperty("--color", color);
});
:root {
--color: red;
}
.overlay-left-a {
color: var(--color);
}
.overlay-left-a:hover {
color: black;
}
<a href="" class="overlay-left-a">test</a>
<a href="" class="overlay-left-a">test</a>
<a href="" class="overlay-left-a">test</a>
<a href="" class="overlay-left-a">test</a>
<div>
<label>
Color name: <input type="text" id="txt-color" value="blue">
</label>
<input type="button" value="Set Color">
</div>

使用另一个类,而不是内联样式,该类使用:not(:hover)表示不将其应用于悬停元素。(:not是否定伪类,您可以在其中放置简单的选择器。(

.overlay-left-a.blue:not(:hover) {
color: blue;
}

document.querySelector("input[type=button]").addEventListener("click", (e) => {
e.currentTarget.disabled = true;
let gr1 = document.getElementsByClassName("overlay-left-a");
for (let i = 0; i < gr1.length; i++) {
gr1[i].classList.add("blue");
}
});
.overlay-left-a {
color:red;
}
.overlay-left-a:hover {
color:black;
}
.overlay-left-a.blue:not(:hover) {
color: blue;
}
<div class="overlay-left-a">hover me</div>
<input type="button" value="Click To Change Color To Blue">


在一条评论中,您表示颜色是动态提供的,因此以上内容不适用于您的特定情况。

要做到这一点,您可以使用一个CSS变量,如mmh4all所示。如果由于某种原因(过时的浏览器或其他原因(无法使用CSS变量,可以在页面中添加style元素:

document.querySelector("input[type=button]").addEventListener("click", (e) => {
// Get the color
const color = document.getElementById("txt-color").value.trim();
// Create or update a style element applying that color
// to `.overlay-left-a` elements
let style = document.getElementById("overlay-left-a-color");
if (!style) {
style = document.createElement("style");
style.id = "overlay-left-a-color";
document.querySelector("head").appendChild(style);
}
style.textContent = `.overlay-left-a:not(:hover) { color: ${color}; }`;
});
.overlay-left-a {
color:red;
}
.overlay-left-a:hover {
color:black;
}
<div class="overlay-left-a">hover me</div>
<label>
Color name: <input type="text" id="txt-color" value="blue">
</label>
<input type="button" value="Set Color">

最新更新