如何为下拉菜单制作过渡效果

问题描述 投票:0回答:1

我在使用 CSS 制作下拉菜单时遇到问题(尝试过 JS,效果相同,但不起作用)。 当我点击按钮打开子菜单时,它会立即出现,如何才能使过渡顺利?

这是 HTML 代码:

<div class="sidenav">
  <a href="#about">About</a>
  <a href="#services">Services</a>
  <a href="#clients">Clients</a>
  <a href="#contact">Contact</a>
  <button class="dropdown-btn">Dropdown 
    <div class="dropdown-arrow">&#9660;
    </div>
  </button>
  <div class="dropdown-container">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
  <a href="#contact">Search</a>
</div>

CSS:

/* Style the sidenav links and the dropdown button */
.sidenav a, .dropdown-btn {
  padding: 8px 0px 0px 0px;
  display: block;
  border: none;
  background: none;
  text-align: left;
    color: #727272;
    text-decoration: underline;
    font-size: 16px;
    line-height: 1.5;
    cursor: pointer;
  outline: none;
}

.dropdown-arrow {
  padding-left: 2px;
    display: inline-block;
    font-size: 9px;
}

/* On mouse-over */
.sidenav a:hover, .dropdown-btn:hover {
  color: #a0a0a0;
}

/* Dropdown container (hidden by default). */
.dropdown-container {
  display: none;
  padding-left: 16px;
}

以及让出现子菜单的JS(它让出现下拉容器):

<script>
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;

for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var dropdownContent = this.nextElementSibling;
    if (dropdownContent.style.display === "block") {
      dropdownContent.style.display = "none";
    } else {
      dropdownContent.style.display = "block";
    }
  });
} 
</script>

首先,我尝试在 CSS 中的

transition: height .4s ease;
内添加
.dropdown-container
行,但什么也没有,它不起作用。 然后我在 JS 代码中添加了相同的转换代码行,如下所示:

<script>
var dropdown = document.getElementsByClassName("dropdown-btn");
var container = document.getElementsByClassName("dropdown-container"); /*ADDED LINE THIS HERE*/
var i;

for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var dropdownContent = this.nextElementSibling;
    if (dropdownContent.style.display === "block") {
      dropdownContent.style.display = "none";
    } else {
      dropdownContent.style.display = "block";
      container.style.transition = "transform 0.4s ease"; /*ADDED LINE THIS HERE*/
    }
  });
} 
</script>

也尝试了

transition: all 0.4s;
,但 all 参数也不起作用。

html css wordpress drop-down-menu menuitem
1个回答
0
投票

您无法转换

display
属性,也无法在固定值(例如零)和
height
之间转换
auto
属性。最简单的选项是转换
opacity
属性以获得淡入淡出效果,或转换
max-height
属性以获得飞入效果。

© www.soinside.com 2019 - 2024. All rights reserved.