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

uelo1irk  于 2023-11-17  发布在  WordPress
关注(0)|答案(2)|浏览(114)

我有一个问题,使用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>


首先,我尝试在.dropdown-container内部的CSS中添加transition: height .4s ease;行,什么都没有,它不起作用。然后我在JS代码中添加了相同的transition代码行,如下所示:

<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参数也不起作用。

efzxgjgh

efzxgjgh1#

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

l0oc07j2

l0oc07j22#

显示风格很难给予过渡。请改变高度。这是有意义的。祝你好运。

for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function () {
    this.classList.toggle("active");
    var dropdownContent = this.nextElementSibling;
    const height = 100;
    const prevHeight = Number(dropdownContent.style.height.split('px')[0]) || 0;
    dropdownContent.style.height = height - prevHeight;
  });
}

个字符

相关问题