我使用徘徊, 活跃的和禁用来设置按钮的样式。
但问题是,当按钮被禁用时,悬停和活动样式仍然适用。
如何应用悬停和活动仅在启用按钮?
你可以使用:启用伪类,但是注意IE<9不支持它:
IE<9
button:hover:enabled{ /*your styles*/ } button:active:enabled{ /*your styles*/ }
一种方法是添加一个特定的类,同时禁用按钮,并覆盖css中该类的悬停和活动状态。或者在css中禁用和指定悬停和活动伪属性时删除一个类。不管怎样,它可能不能完全用css完成,你需要使用一点js。
为什么不在css中使用属性“disabled”。这必须适用于所有浏览器。
button[disabled]:hover { background: red; } button:hover { background: lime; }
.button:active:hover:not([disabled]) { /*your styles*/ }
你可以试试这个。
在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; } }
如果你正在使用LESS或Sass,你可以尝试这样做:
LESS
Sass
.btn { &[disabled] { opacity: 0.6; } &:hover, &:active { &:not([disabled]) { background-color: darken($orange, 15); } } }
使用最轻的触摸:通过规则顺序覆盖。
.btn { /* base styles */ } .btn:hover { color: red; } .btn:active { color: green; } .btn:disabled { color: #aaa; }
诀窍在于顺序——首先应用所有非禁用状态,确保它们都具有相同的特异性,最后应用禁用状态,具有相同的特异性。
对于添加到链接或非交互式元素中的类,这将不起作用,因为它们没有disabled属性。
disabled
(已编辑以删除更高特异性的规则,并与pointer-events混淆)
pointer-events
我在我的项目中使用了下面的一个。
.bg-brand-3 { background-color: black; &[type="button"]:enabled { &:hover { background-color: orange; } &:active { background-color: green; } } &[type="submit"] { // css } }
:enable与:not(:disabled)具有相同的含义
:enable
:not(:disabled)
当我找到一个最简单的方法时,我一直在寻找它。
对于纯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; } } }