252

I use hover, active and disabled to style Buttons.

But the problem is when the button is disabled the hover and active styles still applies.

How to apply hover and active only on enabled buttons?

4

8 回答 8

447

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

button:hover:enabled{
    /*your styles*/
}
button:active:enabled{
    /*your styles*/
}
于 2012-07-22T13:32:48.510 回答
105
.button:active:hover:not([disabled]) {
    /*your styles*/
}

你可以试试这个。。

于 2014-05-09T10:34:34.843 回答
40

为什么不在 css 中使用属性“禁用”。这必须适用于所有浏览器。

button[disabled]:hover {
    background: red;
}
button:hover {
    background: lime;
}
于 2013-12-02T06:29:12.380 回答
24

如果你使用LESSor Sass,你可以试试这个:

.btn {
  &[disabled] {
    opacity: 0.6;
  }
  &:hover, &:active {
    &:not([disabled]) {
      background-color: darken($orange, 15);
    }
  }
}
于 2015-06-11T07:43:45.250 回答
16

在 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;
  }
}
于 2014-09-19T21:42:14.777 回答
16

使用最轻的触摸:通过规则顺序覆盖。

.btn {
  /* base styles */
}

.btn:hover {
  color: red;
}

.btn:active {
  color: green;
}

.btn:disabled {
  color: #aaa;
}

诀窍是顺序——首先应用所有非禁用状态,确保它们都具有相同的特异性,最后禁用,具有相同的特异性。

这不适用于添加到没有该disabled属性的链接或非交互式元素的类。

(编辑删除更高特异性的规则,并弄乱pointer-events

于 2016-09-19T15:48:46.277 回答
2

One way is to add a partcular class while disabling buttons and overriding the hover and active states for that class in css. Or removing a class when disabling and specifying the hover and active pseudo properties on that class only in css. Either way, it likely cannot be done purely with css, you'll need to use a bit of js.

于 2012-07-22T13:37:26.337 回答
0

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

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

:enable含义与:not(:disabled)

于 2021-10-05T04:41:57.197 回答