我使用悬停,激活和禁用样式按钮。

但问题是,当按钮被禁用时,悬停和活动样式仍然适用。

如何应用悬停和活动仅在启用按钮?


当前回答

当我找到一个最简单的方法时,我一直在寻找它。

对于纯CSS:

.button {
  background-color: #222222;
  color: #ffffff;
}

.button:hover {
  background-color: #111111;
}

.button:active {
  background-color: #000000;
}

.button:disabled {
  opacity: 0.5;
}

.button:disabled:hover {
  /*To see no effect except the disabled ones, resets the effects of hover to default of button*/
  background-color: #222222;
  color: #ffffff;
}

SCSS:

.button{
  background-color: #222222;
  color: ffffff;
  &:hover{
    background: #111111;
  }
  &:active{
    background: #000000;
  }
  &:disabled{
    opacity: 0.5;
    &:hover{
      /*To see no effect except the disabled ones, resets the effects of hover to default of button*/
      background-color: #222222;
      color: #ffffff;
    }
  }
}

其他回答

在sass (scss)中:

 button {
  color: white;
  cursor: pointer;
  border-radius: 4px;

  &:disabled{
    opacity: 0.4;

    &:hover{
      opacity: 0.4;  //this is what you want
    }
  }

  &:hover{
    opacity: 0.9;
  }
}

你可以使用:enabled伪类,但注意IE<9不支持它:

button:hover:enabled{
    /*your styles*/
}
button:active:enabled{
    /*your styles*/
}

我在我的项目中使用了下面的一个。

.bg-brand-3 {
  background-color: black;
  &[type="button"]:enabled {
    &:hover {
      background-color: orange;
    }
    &:active {
      background-color: green;
    }
  }
  &[type="submit"] {
    // css
  }
}

:enable与:not(:disabled)含义相同。

如果你正在使用LESS或Sass,你可以试试这个:

.btn {
  &[disabled] {
    opacity: 0.6;
  }
  &:hover, &:active {
    &:not([disabled]) {
      background-color: darken($orange, 15);
    }
  }
}

一种方法是添加一个特定的类,同时禁用按钮,并覆盖css中该类的悬停和活动状态。或者在css中禁用和指定悬停和活动伪属性时删除一个类。不管怎样,它可能不能完全用css完成,你需要使用一点js。