Can I stop :hover from being applied to an element

2020-05-21 08:10发布

Let's say I have some CSS...

button:hover { font-weight: bold }

How can I prevent the :hover styles from being applied, at will? My target use case is when the element is disabled. For example, with this HTML...

<button disabled>Click me</button>

...the :hover CSS is still applied. The button gets faded out but the :hover effect can still be seen. How can this be stopped?

标签: html css
7条回答
ゆ 、 Hurt°
2楼-- · 2020-05-21 08:56

I've just been struggling with this problem and came up with a solution using the css3 not selector. It's not supported by the older IE browsers but you can use selectivizr.js (or another) to add the functionality

button {
  // styles for  non-disabled buttons
}

button:hover:not([disabled]) {
  // styles for hover on non-disabled
}

button[disabled] {
  cursor: default;
}
查看更多
Emotional °昔
3楼-- · 2020-05-21 09:07

Make the hover style the same as the default. Use a class name to turn this feature on or off.

<button class="disabled" disabled>Click me</button>

button.disabled:hover { font-weight: inherit}
查看更多
在下西门庆
4楼-- · 2020-05-21 09:10

I don't think there is a way to truly ignore a set of styles.

You could, however, create a more specific style that overrides the hover styles.

button[disabled]:hover {
  /* turn off button hover styles */
}
查看更多
Emotional °昔
5楼-- · 2020-05-21 09:13

After reading the responses available I found none of them would be suitable for me. I kept thinking there must be a simple solution to this. In the end I just chained the pseudo classes. This worked perfectly.

button:enabled:hover { font-weight: bold }

Example:

.hov:hover { color: red }
.hov2:enabled:hover { color: green }
<p>Without fix</p>
<button class="hov">Hover me</button>
<button class="hov" disabled>Hover me</button>
<p>With fix</p>
<button class="hov2">Hover me</button>
<button class="hov2" disabled>Hover me</button>

Noticed I'm using if enabled pseudo code (:) and the hover pseudo code (:) code to perform the css.

I appreciated it's some time since this thread was opened, but thought it might help others.

查看更多
够拽才男人
6楼-- · 2020-05-21 09:13

Put the property 'transform: none' in your overridden button class.

查看更多
一纸荒年 Trace。
7楼-- · 2020-05-21 09:14

pointer-events: none will disable all hover behavior. very usefull for disabled elements

 button[disabled] { 
      pointer-events: none;

    }
查看更多
登录 后发表回答