How to apply child:hover but not parent:hover(如何应用 child:hover 但不是 parent:hover)
问题描述
使用以下 html,当我将鼠标悬停在子项上时,我会在父项上获得绿色背景.我怎样才能阻止这种情况发生?如果我悬停在子元素之外,我确实想要绿色背景.
With the following html, when I hover over child, I get a green background on parent. How can I stop that from happening? I do want the green background if I am hovering outside of the child element.
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;
}
<div class="parent">
<div class="child">Child</div>
</div>
推荐答案
所以这真的很难看,但它确实有效(有点).我基本上是在创建父母的副本作为孩子的兄弟姐妹.parent-overwrite 默认隐藏,然后在 child 悬停时显示.Chrome 不喜欢它,除非您使用 + 选择器而不是 ~ 选择器.这不是很可扩展,但它可能会起作用.
So this is REALLY ugly, but it works (kind of). I'm basically creating a duplicate of parent as a sibling of child. parent-overwrite is hidden by default, then displayed on the hover of child. Chrome doesn't like it unless you use the + selector instead of the ~ selector. This isn't very scalable, but it may work.
正如其他人所说,javascript 可能是更好的解决方案.
As the other guys posted, javascript would likely be a better solution.
<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>
这篇关于如何应用 child:hover 但不是 parent:hover的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何应用 child:hover 但不是 parent:hover
基础教程推荐
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06