z-index不适用于嵌套的绝对元素

时间:2016-08-24 15:35:58

标签: javascript html css css-position z-index

我正在尝试开发一个包含可扩展的ul列表的下拉列表。默认情况下,列表的元素是可见的。展开列表时,所有元素都应该是可见的,并且应该放在下拉列表上。我附上了代码段,正如您所看到的,列表会展开,但li元素不在下拉列表中,即使ul具有绝对位置和更大z-index

var dropdown = false;
var list = false;

function toggleList () {
  toggle('.hidden', list);
  list = !list;
}

function toggleDropdown () {
  toggle('.dropdown', dropdown);
  dropdown = !dropdown;
}

function toggle (selector, isAlreadyOpened) {
  if(isAlreadyOpened) $(selector).hide();
  else $(selector).show();
}
.parent {
  position: relative;
  background-color: red;
  width: 50%;
}

.dropdown {
  width: 40%;
  height: 100px;
  background-color: blue;
  display: none;
  position: absolute;
  right: 0;
  z-index: 10;
  overflow: hidden;
}

.list {
  position: absolute;
  z-index: 20;
}

.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="parent">
  <button onclick="toggleDropdown()">Toggle dropdown</button>
  
  <div class="dropdown">
    First Dropdown
    
    <button onclick="toggleList()">Toggle list</button>
    <ul class="list">
      <li>1st element</li>
      <li class="hidden">2nd element</li>
      <li class="hidden">3rd element</li>
      <li class="hidden">4th element</li>
      <li class="hidden">5th element</li>
      <li class="hidden">6th element</li>
    </ul>
  </div>
</div>

有人知道如何帮助吗? 谢谢!

2 个答案:

答案 0 :(得分:3)

overflow: hidden移除.dropdown,然后你去!

&#13;
&#13;
var dropdown = false;
var list = false;

function toggleList () {
  toggle('.hidden', list);
  list = !list;
}

function toggleDropdown () {
  toggle('.dropdown', dropdown);
  dropdown = !dropdown;
}

function toggle (selector, isAlreadyOpened) {
  if(isAlreadyOpened) $(selector).hide();
  else $(selector).show();
}
&#13;
.parent {
  position: relative;
  background-color: red;
  width: 50%;
}

.dropdown {
  width: 40%;
  height: 100px;
  background-color: blue;
  display: none;
  position: absolute;
  right: 0;
  z-index: 10;
}

.list {
  position: absolute;
  z-index: 20;
}

.hidden {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="parent">
  <button onclick="toggleDropdown()">Toggle dropdown</button>
  
  <div class="dropdown">
    First Dropdown
    
    <button onclick="toggleList()">Toggle list</button>
    <ul class="list">
      <li>1st element</li>
      <li class="hidden">2nd element</li>
      <li class="hidden">3rd element</li>
      <li class="hidden">4th element</li>
      <li class="hidden">5th element</li>
      <li class="hidden">6th element</li>
    </ul>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

嗯,我其实感到有点愚蠢。我回到我的代码中,注意到overflow: hidden元素上的.dropdown。我删除它并修复了问题。