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

后端 未结 12 926
暖寄归人
暖寄归人 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:01

    There doesn't seem to any CSS way to handle this case. (not sure about CSS4, the way Amit has suggested.) So here is JQuery way.

    The idea is you handle mousedown and mouseup events at 3 levels:

    1. the parent div
    2. the button where you don't want the active state propagated to parent div (".btn1" in the example below)
    3. any other children except the button in second condition. (".btn2" in the example below)

    JS Fiddle

    HTML:

    JQuery:

    $(function(){
        $('div').each(function(e){
            $(this).mousedown(function(e){
                $(this).addClass("activeClass");
            }).mouseup(function(e){
                $(this).removeClass("activeClass");
            });
        });
        $('div .btn1').each(function(e){
            $(this).mousedown(function(e){
                e.stopPropagation();
            }).mouseup(function(e){
                e.stopPropagation();
            });
        });
        $('div :not(.btn1)').each(function(e){
            $(this).mousedown(function(e){
                $(this).parent().addClass("activeClass");
            }).mouseup(function(e){
                $(this).parent().removeClass("activeClass");
            });
        });
    });
    

    CSS:

    div {
      width: 200px;
      height: 200px;
      background-color: #eee;
      border: 1px solid black;
    }
    .activeClass {
      background-color: red;
    }
    

提交回复
热议问题