css - CSS:将最大高度设置为与“无”最大高度时高度相同的值?
问题描述
因此,我正在制作一个使用最大高度和不透明度过渡的下拉菜单,例如,如果下拉菜单的高度为 500 像素,我将在打开时使用 500px 作为最大高度,在关闭时使用 0。但是,我的下拉菜单的高度是自动计算的。我需要将 max-height 设置为此自动计算的高度,以便过渡具有正确的时间。否则,如果我使用更大的 max-height 值,则在关闭时下拉菜单不会移动,直到 max-height 低于真实值,然后在剩余时间内突然移动得更快。有什么办法可以做到这一点?
解决方案
所以我找到了解决方案。我只是在触发关闭下拉列表之前将其设置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 };
}
推荐阅读
- javascript - 确定在 if 条件中使用的布尔表达式中哪个条件为真
- java - 下面的代码是在我每次单击按钮时显示随机颜色。但尽管已完全编译,但它无法正常工作。谢谢
- c++ - 启动新对象时取消对新对象的引用
- mysql - MySQL ON DUPLICATE KEY UPDATE 与所有变量
- r - R分组数据框:函数将单个值与组的其他值相关联
- c# - System.FormatException 格式正确 C#
- svg - CSS 变量 - 如何在同一个属性上使用多个变量?
- vue.js - Vuetify 复选框:如何停止点击事件?
- node.js - Heroku 上的 NodeJs/ExpressJs 应用程序错误
- javascript - 如何在一定时间后使画布中的圆圈消失?