【问题标题】:Displaying a div on top of another without using z-index在不使用 z-index 的情况下在另一个上显示一个 div
【发布时间】:2016-03-11 20:23:18
【问题描述】:

我创建了自定义下拉菜单,其中一个 <div> 保存当前值并充当 <select> 字段,另一个在其下方,当点击顶部时显示,保存所有 <option> 值.

该设计要求底部<div> 稍微低于上面的位置(奇怪的圆角等),所以我使用z-index 来实现这一点。这一切都有效,直到我有两个彼此靠近的下拉菜单。如果单击上面的选项,则会显示下拉选项列表,但它也会位于第二个下拉菜单的下方,这是非常不可取的。这是 jsfiddle 中的简化版本: jsFiddle

如您所见,第一个下拉菜单很好,但第二个隐藏在第三个下方。有什么想法可以实现这一点,以便第二个菜单也能正常工作吗?可能不使用 z-index 吗?

【问题讨论】:

  • 一次可以打开多个下拉菜单吗?在您的示例中,有两个是开放的,但是,在实践中会是这样吗?
  • 两个不能同时打开。如果你检查 jsFiddle 你会看到第三个没有打开,但第二个仍然隐藏在它下面。我将第一个显示为已打开只是为了表明它与其他的相距甚远,但实际上这不会发生。其他两个的问题仍然存在。

标签: html css drop-down-menu z-index overlap


【解决方案1】:

首先,将每个菜单包装在一个元素中。我用了div.container

由于一次只打开一个菜单,只需更改每个容器中.major.minor 元素的z-index(在我的示例中悬停)即可正常工作:

.major {
  position: relative;
  width: 100px;
  background-color: red;
  z-index: 1;
}
.minor {
  position: absolute;
  width: 150px;
  background-color: blue;
  padding-top: 10px;
  margin-top: -10px;
  z-index: 0;
  display: none;
}
.container:hover .major {
  z-index: 5;
}
.container:hover .minor {
  display: block;
  z-index: 4;
}
.moveup {
  margin-top: -25px;
}
<div class="container">
  <div class="major">
    First one fine
  </div>
  <div class="minor">
    Option part goes here Option part goes here Option part goes here
  </div>
</div>
<br />
<br />
<br />
<br />
<div class="container">
  <div class="major">
    Second menu
  </div>
  <div class="minor">
    Option part goes here Option part goes here Option part goes here
  </div>
</div>
<div class="container">
  <div class="major">
    Third menu
  </div>
  <div class="minor">
    Option part goes here Option part goes here Option part goes here
  </div>
</div>

【讨论】:

    【解决方案2】:

    我不是 100% 确定你的意思,但如果我没记错的话,解决方案应该是包装 .major 和 .minor div,这样它们就不会相互重叠,如下所示:

    <div class="dropdown">
      <div class="major">
      First one fine
      </div>
      <div class="minor">
      Option part goes here
      Option part goes here
      Option part goes here
      </div>
    </div>
    

    查看我的 JSFiddle 分支:https://jsfiddle.net/jk1dn4yx/

    【讨论】:

    • 不起作用:jsfiddle.net/jk1dn4yx/1 两个 .major 部分可以在另一个之下,我无法控制它,当不显示下拉菜单时它实际上很好。但是,只要您单击上面的那个(在演示中不可用,我直接显示它在那里打开),蓝色部分就可见,它位于下面的红色 div 后面,这实际上是问题......
    • 但是你可以添加一个包装div吗?如果您在打开 .minor div 时还添加了一个类,例如“open”,请尝试这个扩展的 z-index 解决方案:jsfiddle.net/jk1dn4yx/2 也可以尝试 Hatchet 的解决方案,这似乎基本上是我为这个评论所做的,在我看到之前哈切特的回答。 :)
    • 是的,不过他也在更改 z-index,这应该可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    相关资源
    最近更新 更多