css - 较高的 z-index 框,不与较低的 z-index 框重叠

标签 css

当 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 比 box1z-index 高,但是因为你把它放在一个 box1z-index 以某种方式重置。

这意味着您在 box1 中提供 <2 z-index 的所有内容都会隐藏在 box2 下。

这个问题可以通过两种方式解决:纯 CSS 或使用 jQuery。

CSS

在 CSS 中,这很简单:只需在鼠标悬停时更改 box1z-index,如下所示:

.box1:hover {
    z-index: 3;
}

这将使您悬停的当前 box1 具有比页面上其他 box1 更高的 z-index。我还在 box2 上添加了一个小的 hover 效果,以获得更多您想要的最终产品。

工作 fiddle

jQuery

在 jQuery 中,它比必要的复杂一点,但结果与上面相同(我会选择 CSS 解决方案)。下面的代码片段执行以下操作:

When the mouse hovers on .box1, it adds a z-index: 3 to that specific box1, but ONLY if it contains a div with the class box2.

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/

相关文章:

html - 包含悬停操作的复杂 div 集的定位问题?

css - 将表格宽度从 100% 更改为 75% 时出现问题

javascript - 设置 td 以便它通过 onclick 链接到 javascript

css - 调整浏览器大小时防止 div 继续移动

html - Bootstrap 嵌套列利用推/拉

javascript - 如何使用 jQuery 检查页面上的 IFrame 是否可见

html - 提交按钮上的图像

css - flex-basis 属性集究竟是什么?

javascript - 使用 append() 动态添加一个 div

html - 为什么我的 slider 堆叠在一起? slider 新手