【问题标题】:CSS transitions doesn't work with height property [duplicate]CSS过渡不适用于height属性[重复]
【发布时间】:2014-09-14 13:37:18
【问题描述】:

我正在尝试创建一个带有过渡的简单菜单。当您单击菜单项时,它应该以 CSS 过渡打开,但我猜我错过了一些东西。我的 CSS 类是:

.container {
    height: 0;
    overflow: hidden;
    transition: all 0.3s;
    -webkit-transition: all 0.6s;
}

.container div {
    font-size: 13px;
    padding: 5px;
}

.ShowSubMenu {
    height: initial !important;
}

ShowSubMenu 仅在单击外部菜单项时应用。请在此处查看一个工作示例:http://jsfiddle.net/CwmTZ/

如果将 ShowSubMenu 的 height 属性切换为常数,则过渡效果会很好。问题是,我不知道我会有多少子菜单项,它必须是动态的。

谢谢!

【问题讨论】:

  • 您不能使用 CSS 转换到 autoinitial 高度...您需要 JS/JQ 或使用 max-height。

标签: html css css-transitions


【解决方案1】:

此值:height: initial !important; 不能使用 CSS 制作动画。您只能转换数值。

你可以像this一样解决它:

.container {
    max-height: 0;
    overflow: hidden;
    transition: all 0.3s;
    -webkit-transition: all 0.6s;
}

.ShowSubMenu {
    background: #f00;
    max-height: 200px; /* Something bigger than menu */
    height: initial;
}

Fiddle

【讨论】:

  • 这似乎运作良好,但看起来过渡不平滑并受最大高度值的影响(尝试将 200px 更改为 1000px)。有什么建议吗?
  • 还没有看到任何不是黑客的解决方案。也许最好的办法是用 JS 计算高度...
【解决方案2】:

我创建了一个函数来计算container 元素的总高度。

js

$(function() {
    $('.Menu').on('click',function() { 
        if ($('.container').hasClass('ShowSubMenu'))
            $('.container').height(findHeight());
        else
            $('.container').height(findHeight());
    });
});

function findHeight(){
    var sumHeight = 0;
     $('.container').children().each(
         function(){
             sumHeight += $(this).outerHeight();
         });
    return sumHeight;
}

fiddle

还有一个菜单中有更多项目的示例:

fiddle

【讨论】:

  • 感谢您的回答,但我想避免这种计算
猜你喜欢
  • 2021-10-23
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 2014-10-14
  • 2020-04-30
  • 2014-04-01
  • 2020-09-23
  • 1970-01-01
相关资源
最近更新 更多