悬停在子级上而对父级没有悬停效果[重复]
Posted
技术标签:
【中文标题】悬停在子级上而对父级没有悬停效果[重复]【英文标题】:hover on child without hover effect on parent [duplicate] 【发布时间】:2013-07-29 05:40:10 【问题描述】:所以我有 2 个div
,他们在彼此中,就像这样
<div class="parent">
<div class="child"></div>
</div>
当我将鼠标悬停在 .parent
上时,我想将 background
从 .parent
更改。
但是当我将鼠标悬停在.child
上时,我希望background
再次恢复正常。
例如:(或http://jsfiddle.net/k3Zdt/1/)
.parent
transition:background-color 1s;
width:100px;
height:100px;
background:#3D6AA2;
padding:50px;
.parent:hover
background:#FFF;
.child
height:100px;
width:100px;
background:#355E95;
transition:background-color 1s;
.child:hover
background:#000;
<div class="parent">
<div class="child">
</div>
</div>
当我将鼠标悬停在深蓝色区域上时,我希望不太深蓝色的区域保持不太深蓝色而不是变为白色。
我想保留这个<div>
结构。而且我不想要 javascript 解决方案(我知道 JavaScript 解决方案,但我想保持纯 CSS)。
【问题讨论】:
将 div 并排放置并使用定位将它们视为父子元素。 不要相信你可以使用 CSS 并保持相同的 html 结构...悬停在子级上总是会触发父级的悬停。您将不得不使用不同的结构或以另一种方式伪造它。对于这个例子,这不是问题,但我认为对于更复杂的设置来说这是一个问题。 "我想保留这个<div>
结构" 我不想用 CSS 做奇怪的定位。待定。
@robooneus 我认为它也不会,但也许还有一些我不知道的东西。
这里是Fiddle。
【参考方案1】:
基本上你不能:How to style the parent element when hovering a child element?
但一个技巧是使用兄弟元素: http://jsfiddle.net/k3Zdt/8/
.parent
width: 100px;
height: 100px;
padding: 50px;
.child
height: 100px;
width: 100px;
background: #355E95;
transition: background-color 1s;
position: relative;
top: -200px;
.child:hover
background: #000;
.sibling
position: relative;
width: 100px;
height: 100px;
padding: 50px;
top: -50px;
left: -50px;
background: #3D6AA2;
transition: background-color 1s;
.sibling:hover
background: #FFF;
<div class="parent">
<div class="sibling"></div>
<div class="child"></div>
</div>
【讨论】:
谢谢 :) 就是这样。这是我的最终结果 :) jsfiddle.net/k3Zdt/11【参考方案2】:你可以欺骗一些东西;)
基本上,为子 div 使用 :before
伪元素,大小相同;
当您将鼠标悬停在子 div 上时,放大 :before
伪元素以覆盖父 div 区域;这会导致父divhover
效果掉下来,然后又回到原来的状态。还涉及到 z-index 的精确组合。
演示:http://jsfiddle.net/gFu8h/ Dark Magic(tm)
.parent
width: 100px;
height: 100px;
padding: 50px;
transition: background-color 1s;
background: #3D6AA2;
position: relative;
z-index: 1;
.parent:hover
background: #FFF;
.child
height: 100px;
width: 100px;
background: #355E95;
transition: background-color 1s;
position: relative;
.child:hover
background: #000;
.child:before
content: '';
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
z-index: -1;
transition: background-color 1s;
.child:hover:before
top: -50px;
bottom: -50px;
left: -50px;
right: -50px;
background: #3D6AA2;
<div class="parent">
<div class="child"></div>
</div>
【讨论】:
+1 酷.. 没想到。 :) 谢谢;这只是一个概念验证,如果需要,它应该被调整为更具动态性并更恰当地处理悬停(它只有在离开父亲时才恢复状态(那不再是父亲了) ,因为它是透明的:before
放大)),但至少......纯CSS是可能的:)以上是关于悬停在子级上而对父级没有悬停效果[重复]的主要内容,如果未能解决你的问题,请参考以下文章
为啥当我在 grails 上删除一对多关系上的父级时,会在子级上调用 beforeInsert 事件?