gpt4 book ai didi

javascript - 使用 JavaScript 添加类后 CSS 样式不会改变

转载 作者:行者123 更新时间:2023-12-05 00:35:49 24 4
gpt4 key购买 nike

我正在尝试构建一个选择菜单,并且我想在单击按钮时更改按钮的背景颜色。我正在使用下面的代码来应用 sort-select-active类到divsort-select ID:

var selected = false;
var select= document.getElementById('sort-select')
select.onclick = (e) => {
selected = !selected;
if (selected)
select.classList.add("sort-select-active");
else
select.classList.remove("sort-select-active");
};
#sort-select {
background-color: lightgray;
}

.sort-select-active {
background-color: grey;
}
<div id="sort-contain">
<div id="sort-select">
Selected
</div>
</div>

该类已成功添加到元素中,但背景颜色没有改变。定义的不同背景颜色之间是否存在冲突?

最佳答案

您设置了 background-color通过 id ,然后您通过 class 设置另一个,将始终应用第一个,因为它具有更高的 specificity .更改#sort-select选择器由 class在您的 CSS 中,或使用这样的内联样式:

var selected = false;
select.onclick = (e) => {
selected = !selected;
if (selected)
slect.style.backgroundColor ="gray"
else
slect.style.backgroundColor ="lightgray"
};
你也可以使用 !important关键字,像这样:
.sort-select-active {
background-color: grey!important;
}

关于javascript - 使用 JavaScript 添加类后 CSS 样式不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70591846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com