【问题标题】:CSS hover on a div, but not if hover on his children [duplicate]CSS悬停在div上,但如果悬停在他的孩子身上则不会[重复]
【发布时间】:2014-04-11 18:43:26
【问题描述】:

我查看了这个问题是否已经被回答,但找不到任何东西,只有关于我正在寻找的反向 css 规则的问题。

我有一个包含一个或多个子元素的 div,我希望它在悬停时更改其背景,但如果悬停其中一个子项则不会;我需要将 :hover 规则限制为纯元素,而不是它包含的后代。不是 CSS 中的父规则,并且每当鼠标经过父项及其子项时都会触发 :hover,我发现自己没有想法,也许仅使用 CSS 无法实现此结果。 但是,问题是关于 CSS 的,所以不需要 JS 或 JQuery 解决方案(我可以自己提供)

代码:

HTML

    <div class="parent">Text of the parent
        <p class="class1">I do not need to trigger parent's background color change!</p>
    </div>

CSS

    .parent {
       background: #ffffff;
    }
    .parent:hover {
       background: #aaaaff;
    }
    .class1 {
       margin: 10px;
    }

【问题讨论】:

    标签: css hover children


    【解决方案1】:

    您可以简单地通过将此属性添加到子类 CSS 来实现。

    pointer-events: none;
    

    这对我有用。

    【讨论】:

    • 这似乎适用于我在 Safari 中的情况
    • 此方法似乎禁用了附加到应用它的元素的所有事件。
    • 我的朋友,你是天才:)
    【解决方案2】:

    当前无法使用我们拥有的 CSS 选择器(this is as close as we can get without javascript)在子项悬停时停止元素的悬停效果 - 除了影响父项之外,还影响悬停时的子项。这只有在孩子的宽度和高度是父母的 100% 时才有效

    the CSS selectors level 4 draft 中有一个父选择器!,可以在如下情况下使用:

    .parent! .class1:hover {
       background: #ffffff;
    }
    

    但我们还没有这种能力。

    【讨论】:

    【解决方案3】:

    Fiddle 基于this answer

    <style>
        .parent { padding: 100px; width: 400px; height:400px; position: relative; z-index: 998; }
        .parent:hover { background-color: green; }
        .child { padding: 100px; width: 200px; height:200px; position: relative; z-index: 1000; }
        .child:hover { background-color: blue; }
        .parent-overwrite { padding: inherit; width: inherit; height: inherit; position: absolute; top: 0; left: 0; z-index: 999; background-color: #FFF; display: none; }
        .child:hover ~ .parent-overwrite { display: block; }
    </style>
    
    <div class="parent">
        <div class="child">Child</div>
        <div class="parent-overwrite"></div>
    </div>
    

    你应该在这方面使用 JavaScript。正如 Zack Saucier 已经说过的,目前使用纯 CSS 真的不可能。

    【讨论】:

      【解决方案4】:

      使用纯 CSS 无法做到这一点,但使用 jQuery 很容易实现。 因此,当您将鼠标悬停在子项上时,您不想修改父项。

      https://jsfiddle.net/8nqfLgsk/2/

      $(".list-categories li a").hover( function(){
      
         $(this).toggleClass("active-btn");
      
      });   
      

      基本上,您只是向悬停的元素添加一个类,而不修改父元素。

      【讨论】:

      • 首先你说的是哪个版本的CSS?
      猜你喜欢
      • 2015-02-08
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2022-12-26
      • 1970-01-01
      • 2014-11-15
      相关资源
      最近更新 更多