CSS: Prevent parent element getting :active pseudoclass when child element is clicked

后端 未结 12 903
暖寄归人
暖寄归人 2021-01-07 16:19

JSFiddle

When you click the button, you see that :active pseudoclass is triggered for the parent div. Is ther

12条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 17:13

    This may or may not work for you, but this is how I achieve it with pure CSS. The only caveat is the dependence of focus-within which isn't supported by IE or Edge.

    .parent {
      transition: background-color;
    }
    .parent:active:not(:focus-within) {
      background-color: red;      
      transition-delay: 1ms; // Delay one cycle to allow child to focus 
    }
    

    What's going on here is, the parent element will get the active state, as will the child that gets clicked. The only difference is that the focus will apply to the child element, but only on the next cycle. To circumvent any animations from while in this 2 step process, apply a 1ms delay. The next cycle, the element will be active, but the focus will be applied to the child. Thus, the parent will not apply the transition. I would imagine animation delay: 1ms would work the same way.

    Another alternative is to give the item a tabindex=-1 attribute and use

    .parent {
      transition: background-color;
    }
    .parent:active:focus {
      background-color: red;      
    }
    

    The only issue with this is the fact it may change keyboard navigation behavior and relies on some HTML as well. If you do want keyboard navigation use tabindex=0 or any value besides -1. But there's no JS used.

    There are some nice polyfills for focus-within that you can use for IE/Edge but that would go outside "CSS Only".

    But, we can put both of them together to create this:

    .parent {
      transition: background-color;
    }
    
    .parent[tabindex]:active:focus {
      background-color: red;
    }
    
    .parent:active:not(:focus):not(:focus-within) {
      background-color: red;
      transition-delay: 1ms;
    }
    

    This works on IE11, Edge, and Chrome.

    http://jsfiddle.net/s0at4w4b/42/

提交回复
热议问题