下拉菜单无法正常工作。 (html)

时间:2019-05-02 14:44:04

标签: javascript html css

im使我的网站仅使用html代码(没有引导程序)。我想制作一个带有规格列表的下拉列表。问题是,一旦完成打开我的列表的操作,正在浏览的内容就不会在下面移动,因此它在列表上重叠了。看这张照片,看看我有什么。 enter image description here

理想的方法是进行以下操作:enter image description here

所以在这里,当我打开列表时,下面的内容会自动显示在下面(但这是引导程序,所以我不能只复制它,因为我仅使用html)

我的html代码是这样的:

<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#home">Home</a>
    <a href="#about">About</a>
    <a href="#contact">Contact</a>
  </div>
</div>   

还有CSS:

.dropbtn {
  background-color: #3498DB;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

.dropbtn:hover, .dropbtn:focus {
  background-color: #2980B9;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {background-color: #ddd;}

.show {display: block;}

和javascript:

<script>

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
</script>

1 个答案:

答案 0 :(得分:1)

示例:https://codepen.io/anon/pen/VNojBe

  1. position: absolute;移除.dropdown-content
  2. position: relative中更改为.dropdown-content
相关问题