当 box2 的 z-index 高于 box1 时,为什么 box2 不与其下方的 box1 重叠?
.box1 {
height: 30px;
width: auto;
z-index: 1;
position: relative;
}
.box2 {
position: absolute;
height: 20px;
border: 1px solid red;
background-color: white;
z-index: 2;
}
<div class='box1'>
Just a box
<div class='box2'>Should overlap</div>
</div>
<div class='box1'>
Why is this not partially hidden?
</div>
这是一个 fiddle :http://jsfiddle.net/k7m4y42L/ 另一个类似于我的 HTML 结构:http://jsfiddle.net/1nv8fd93/
最佳答案
你给 box2
的 z-index 比 box1
的 z-index
高,但是因为你把它放在一个 box1
,z-index
以某种方式重置。
这意味着您在 box1
中提供 <2 z-index 的所有内容都会隐藏在 box2
下。
这个问题可以通过两种方式解决:纯 CSS 或使用 jQuery。
CSS
在 CSS 中,这很简单:只需在鼠标悬停时更改 box1
的 z-index
,如下所示:
.box1:hover {
z-index: 3;
}
这将使您悬停的当前 box1
具有比页面上其他 box1
更高的 z-index
。我还在 box2
上添加了一个小的 hover
效果,以获得更多您想要的最终产品。
工作 fiddle
jQuery
在 jQuery 中,它比必要的复杂一点,但结果与上面相同(我会选择 CSS 解决方案)。下面的代码片段执行以下操作:
When the mouse hovers on
.box1
, it adds az-index: 3
to that specificbox1
, but ONLY if it contains a div with the classbox2
.
jQuery
$('.box1').mouseover(function() {
$(this).has(".box2").css('z-index', 3);
});
工作 fiddle .
在某种程度上,上面只是一个非常复杂的:hover
效果。只是在做出这个解决方案之后,我才考虑在 box1
上添加一个 :hover
并调整 z-index
。但由于它可能对某些人有用(可能没有),所以我将其留在答案中。
关于css - 较高的 z-index 框,不与较低的 z-index 框重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31475074/