使用以下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)
现在可以使用:has和:not伪类的组合来实现这一点,表达式如下:
.parent:hover:not(:has(.child:hover)) {}\nRun 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}\nRun Code Online (Sandbox Code Playgroud)\n原始代码片段的工作修改如下:
\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也可以通过重用.parent选择器代替.child选择器来使其递归。
请参阅此处的浏览器支持。在撰写本文时,所有主要浏览器都支持它\xe2\x80\x94,除了 Firefox,它仍然存在有缺陷的实验实现。
\n所以这真的很难看,但它有效(有点).我基本上创建了父母的副本作为孩子的兄弟姐妹.默认情况下隐藏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)
| 归档时间: |
|
| 查看次数: |
10183 次 |
| 最近记录: |