javascript - 在 javascript 中更改按钮背景时在 HTML 中丢失悬停和活动样式
问题描述
我正在尝试用三个按钮做一个选择栏,在我有悬停和活动的样式中,当单击一个按钮时,背景颜色会随 JS 函数而变化,我的 css 没有 boostrap 或类似的东西,但是当任何单击三个按钮,背景颜色发生变化,但悬停和活动现在没有效果
<!-- This is the bar and below css styling -->
<div class="login_selector_container">
<button class="login_option" id="login_option1" onclick="selectAutor()"></button>
<button class="login_option" id="login_option2" onclick="selectEditor()"></button>
<button class="login_option" id="login_option3" onclick="selectMiembro()"></button>
</div>
.login_option {
padding: 0.5rem 1rem;
background: white;
border-style: none;
font: inherit;
transition: 0.3s;
color: var(--mRed);
}
.login_option:hover {
background: var(--mRed);
color: white;
}
.login_option:active {
background: var(--mLigthRed);
color: white;
}
这是三个JS函数之一
function selectEditor() {
//Changes background to white and font color to red (inactive state)
btnAutor.style.background = "white";
btnAutor.style.color = "var(--mRed)";
//Changes background to red and font color to white (active state)
btnEditor.style.background = "var(--mRed)";
btnEditor.style.color = "white";
//Changes background to white and font color to red (inactive state)
btnMiembro.style.background = "white";
btnMiembro.style.color = "var(--mRed)";
}
谢谢。
解决方案
猜测是因为您的示例中缺少代码。元素样式中的 CSS 取代了类 CSS,因此 :hover 中的背景和颜色不会生效。如果您使用空白字符串清除非活动状态,则 css 类中的 :hover 应该会再次起作用。
function selectEditor() {
//Changes background to white and font color to red (inactive state)
btnAutor.style.background = "";
btnAutor.style.color = "";
//Changes background to red and font color to white (active state)
btnEditor.style.background = "var(--mRed)";
btnEditor.style.color = "white";
//Changes background to white and font color to red (inactive state)
btnMiembro.style.background = "";
btnMiembro.style.color = "";
}
推荐阅读
- jpa - 在 MariaDB 中生成唯一 ID
- windows - 如何在 bat/cmd 中设置变量?
- haskell - 如何为 Haskell 应用指定绑定端口?
- raspberry-pi - RTC DS1307 的 RPi 零 - 远程 I/O 错误
- php - 在浏览器中显示部分输出
- microsoft-dynamics - 了解关系以及在表上建立关系的位置 Microsoft Dynamics Ax 2012
- java - 从`build.gradle`获取值到代码
- java - EntityManagerFactory 已关闭 - 仅在特定机器上
- android - BroadcastReceiver Intent.ACTION_PACKAGE_ADDED/REMOVED Android Oreo
- python - Python 3.6:classmethod 上的 abc.abstracmethod 不检查类级别调用