首页 > 解决方案 > 在 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)";
}

谢谢。

标签: javascripthtmlcss

解决方案


猜测是因为您的示例中缺少代码。元素样式中的 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 = "";
}

推荐阅读