显示/折叠事件时菜单高度的CSS转换

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

我正在使用可折叠菜单制作水平导航栏。我正在使用bootstrap 4angular。单击菜单图标时,折叠/显示效果很好,但是我想绑定一些CSS过渡(缓慢改变高度)。我的简单代码在这里:

<nav class="navbar navbar-expand-md navbar-light bg-light">
  <a class="navbar-brand" href="#">SOME BRAND</a>
  <button id="toggler" class="navbar-toggler collapsed" type="button" data-toggle="collapse" (click)="toogle();" data-target="#menu" aria-controls="menu" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>    
  <div class="navbar-collapse" id="menu" [ngClass]="activeClass ? 'show' : 'collapse'" data-parent="#toggler">
    <ul class="navbar-nav ml-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
    </ul>
  </div>
</nav>

我的CSS是:

.on-slide-down {
    height: 500px;
}
#menu {
    transition: height 1.5s ease;
    height: auto;
    overflow: hidden;
}

并且JS函数是:

toogle(){
    this.activeClass = !this.activeClass;
    let menu:HTMLElement = document.querySelector("#menu");
    menu.classList.toggle("on-slide-down");
  }

所以我的想法是动态绑定类.on-slide-down,这会增加高度。不幸的是,过渡无法正常进行。折叠并显示菜单仍然是默认行为。我正在按照此example进行操作,但是我不知道问题出在哪里。

html css bootstrap-4 css-transitions
1个回答
1
投票

为什么不仅仅覆盖普通的Bootstrap折叠过渡?这样,您就不需要多余的JS:

https://www.codeply.com/go/WJmJoNIlbA

<nav class="navbar navbar-expand-md navbar-light bg-light">
    <a class="navbar-brand" href="#">SOME BRAND</a>
    <button id="toggler" class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#menu" aria-controls="menu" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="navbar-collapse collapse" id="menu" data-parent="#toggler">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
                <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
        </ul>
    </div>
</nav>

CSS:

#menu {
    transition: height 1.5s ease;
}
© www.soinside.com 2019 - 2024. All rights reserved.