【问题标题】:CSS: Set max-height to same value as height becomes when "none" max-height?CSS:将最大高度设置为与“无”最大高度时高度相同的值?
【发布时间】:2021-05-17 06:05:31
【问题描述】:

所以我正在制作一个使用最大高度和不透明度转换的下拉菜单,例如,如果下拉菜单的高度为 500 像素,我将在打开时使用 500px 作为最大高度,在关闭时使用 0。但是,我的下拉菜单的高度是自动计算的。我需要将 max-height 设置为此自动计算的高度,以便过渡具有正确的时间。否则,如果我使用更大的 max-height 值,则在关闭时下拉菜单不会移动,直到 max-height 低于真实值,然后在剩余时间内突然移动得更快。有什么办法吗?

【问题讨论】:

    标签: css animation height dropdown transition


    【解决方案1】:

    所以我找到了解决方案。我只是在触发关闭下拉菜单之前将maxHeight 设置为offsetHeight

    我还需要使用 0 毫秒的 setTimeout 来触发关闭它,尽管在运行以下函数之后。

    export function retreatDropdown(e: HTMLElement) {
      e.style.maxHeight = `${e.offsetHeight}px`;
    }
    

    我可以做一个类似的技巧来打开动画,但在打开之前你不会知道正确的maxHeight,所以我猜这更棘手(但不如关闭动画 IMO 重要)。

    编辑:关闭/打开下拉菜单的完整(TypeScript)解决方案

    const defaultTransitionTime = 200;
    
    export function toggleDropdown(
      e: HTMLElement,
      value: boolean = null,
      toggleAction: () => void = null // Function that toggles true/false for accordion open
    ) {
      if (value) {
        openDropdown(e, toggleAction);
      } else {
        retreatDropdown(e, toggleAction);
      }
    }
    
    export function openDropdown(
      e: HTMLElement,
      openAction: () => void = null
    ) {
      if (openAction) setTimeout(() => openAction(), 0);
      e.style.display = "block";
      setTimeout(() => {
        const offsetHeight = e.offsetHeight;
        e.style.maxHeight = "0px";
        setTimeout(() => {
          e.style.maxHeight = `${offsetHeight}px`;
        }, 5);
      }, 5);
      setTimeout(() => {
        e.style.maxHeight = "none";
      }, defaultTransitionTime);
    }
    
    export function retreatDropdown(
      e: HTMLElement,
      closeAction: () => void = null
    ) {
      e.style.maxHeight = `${e.offsetHeight}px`;
      if (closeAction) setTimeout(() => closeAction(), 0);
    }
    

    下拉 CSS 类:

    .dropdown {
      transition: opacity 200ms linear, max-height 200ms linear;
      will-change: opacity, max-height;
    }
    

    Angular ngStyle(应用于手风琴的打开/关闭):

    elementStyle(e: HTMLElement) {
        return this.isOpen(HTMLElement) // I use a map of booleans for open state here...
          ? { display: "block", "max-height": "none" }
          : { "max-height": 0, opacity: 0 };
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 2021-03-10
      • 2021-06-21
      • 2014-02-15
      • 2019-07-01
      • 2012-12-14
      相关资源
      最近更新 更多