首页 > 解决方案 > CSS:将最大高度设置为与“无”最大高度时高度相同的值?

问题描述

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

标签: cssanimationheightdropdowntransition

解决方案


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

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

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 };
  }

推荐阅读