如何申请孩子:悬停但不是父母:悬停

cas*_*son 11 css hover

使用以下html,当我将鼠标悬停在子项上时,我获得了父项的绿色背景.我怎么能阻止这种情况发生?如果我在子元素之外盘旋,我确实想要绿色背景.

CSS3很好.

.parent {
  padding: 100px;
  width: 400px;
  height: 400px;
}

.parent:hover {
  background-color: green;
}

.child {
  padding: 100px;
  width: 200px;
  height: 200px;
}

.child:hover {
  background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)

Nil*_*son 9

2022 年:

\n

现在可以使用:has:not伪类的组合来实现这一点,表达式如下:

\n
.parent:hover:not(:has(.child:hover)) {}\n
Run Code Online (Sandbox Code Playgroud)\n

分解它:

\n
.parent\n  /* When this element is hovered */\n  :hover \n  /* but it does not */\n  :not(\n    /* have a child node .child, that is also hovered */\n    :has(.child:hover)\n  ) {\n  /* apply these rules */\n}\n
Run Code Online (Sandbox Code Playgroud)\n

原始代码片段的工作修改如下:

\n

\r\n
\r\n
.parent {\n  padding: 100px;\n  width: 400px;\n  height: 400px;\n}\n\n.parent:hover:not(:has(.child:hover)) {\n  background-color: green;\n}\n\n.child {\n  padding: 100px;\n  width: 200px;\n  height: 200px;\n}\n\n.child:hover {\n  background-color: blue;\n}
Run Code Online (Sandbox Code Playgroud)\r\n
<div class="parent">\n  <div class="child">Child</div>\n</div>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

也可以通过重用.parent选择器代替.child选择器来使其递归。

\n

请参阅此处的浏览器支持。在撰写本文时,所有主要浏览器都支持它\xe2\x80\x94,除了 Firefox,它仍然存在有缺陷的实验实现。

\n


Bry*_*ing 8

所以这真的很难看,但它有效(有点).我基本上创建了父母的副本作为孩子的兄弟姐妹.默认情况下隐藏parent-overwrite,然后显示在child的悬停上.Chrome不喜欢它,除非您使用+选择器而不是〜选择器.这不是很可扩展,但可能有效.

正如其他人发布的那样,javascript可能是更好的解决方案.

 <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>
Run Code Online (Sandbox Code Playgroud)

  • 哈哈哈谢谢,这是一个有趣的问题需要解决.我之前完全遇到过这个完全相同的问题,但我认为我的解决方案是手动更改没有悬停声明的父级的类.这对你不起作用,因为你希望你的父母悬停仍然工作.我的程序员认为我会因为这个丑陋丑陋的黑客而受到严厉的贬低.谢谢你证明他错了;) (2认同)