带动画的 CSS 下拉菜单(无 js)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16421711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 22:47:43  来源:igfitidea点击:

CSS Dropdown menu with animation (no js)

css

提问by raininglemons

Trying to create an animated dropdown menu using CSS animation, without any JS. Thought I've been barking up the right tree but can't see where I'm going wrong, for this simplified menu item...

尝试使用 CSS 动画创建动画下拉菜单,而无需任何 JS。以为我一直在咆哮正确的树,但看不出我哪里出错了,对于这个简化的菜单项......

<div class="menu">Menu Item
    <ul>
        <li>Dropdown 1</li>
        <li>Dropdown 2</li>
        <li>Dropdown 3</li>
        <li>Dropdown 4</li>
        <li>Dropdown 5</li>
    </ul>
</div>

And the following CSS;

以及以下 CSS;

.menu ul {
    height: 0px;
    overflow: hidden;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

.menu:hover ul {
    height: auto;
}

Thought that should successfully result in a scroll down of the div, but it just keeps appearing. Any thoughts? Cheers

认为这应该会成功地导致 div 向下滚动,但它只是不断出现。有什么想法吗?干杯

回答by Michael

See this topic for reference: How can I transition height: 0; to height: auto; using CSS?

请参阅此主题以供参考:How can I transition height: 0; 到高度:自动;使用 CSS?

To put it simply, you can not animate to height: auto;. It is not supported. If you have a pre-determined, fixed height, you can do it by animating to that specific value. 0px to 100px for instance. Auto however is not supported.

简而言之,您不能为height: auto;. 不支持。如果您有一个预先确定的固定高度,您可以通过为该特定值设置动画来实现。例如 0px 到 100px。但是不支持自动。

The first answer in the link above links to another article in which a sort of work-around is given. You may explore that for implementation on your site.

上面链接中的第一个答案链接到另一篇文章,其中给出了一种解决方法。您可以探索它以在您的网站上实施。

Can you use CSS3 to transition from height:0 to the variable height of content?

你能用 CSS3 从 height:0 过渡到内容的可变高度吗?

回答by Blazemonger

You can't use CSS transitions with height:auto, only with specific values.

您不能将 CSS 转换与 一起使用height:auto,只能与特定值一起使用。

.menu:hover ul {
    height: 100px;
}

http://jsfiddle.net/mblase75/cWZMu/

http://jsfiddle.net/mblase75/cWZMu/

回答by artecher

The animation for a dropdown can be implemented with pure CSS:

下拉菜单的动画可以用纯 CSS 实现:

ul {
  overflow: hidden;
  transition: all .3s ease;
}

ul.folded {
  max-height: 0;
}

ul.unfolded {
  max-height: 300px; //value of max-height should always bigger than actual sum of all li's height
}