CSS3 过渡以一种方式工作,但不以另一种方式工作

CSS3 transition working one way but not the other

我有一个 <div> 有条件地具有两个 class 之一 -

ng-class="{'visible': sidebarShown, 'hidden': !sidebarShown}"

最初的 class 将永远是 hidden,当 visible 替换那个 class 时,widthleftopacity 属性都使用 CSS3 转换动画。

但是,当 hidden class 替换 visible 时,动画不会反转,所有三个属性的新值都会立即切换。

我已经尝试将 transition 属性 添加到 .visible.hidden 的样式中,以及分别添加到每个样式中,但仅在所有情况下visible 动画有效。

我做错了什么?


相关HTML

<div id="modal" data-ng-if="isMobile"
                data-ng-class="{'visible': sidebarShown, 'hidden': !sidebarShown}">
</div>

CSS 对于 #modal.hidden#madal.visible

.mobile #modal{
    position:   absolute;
}
.mobile #modal.hidden{
    left:       0;
    opacity:    0;
    width:      100%;
}
.mobile #modal.visible{
    background-color:   #000000;
    height:             100%;
    left:               271px;
    opacity:            0.8;
    right:              0;
    width:              calc(100% - 271px);
    z-index:            99;
    -webkit-transition: all 0.5s ease-in-out;
    transition:         all 0.5s ease-in-out;
}

进一步尝试

我现在发现初始缺失 height 是问题所在。下面的代码仍然只能以一种方式工作。

我需要的-

.mobile #modal.hidden  { height: 0; }
.mobile #modal.visible { height: 100%; }

当从 .hidden 过渡到 .visible 时,height 的值应该立即改变。然而,以另一种方式 height 应该在延迟 0.5s 后转换,从而允许其他动画完成。我想出了下面的代码,但它仍然不完整。

.mobile #modal{
    left:               0;
    opacity:            0;
    position:           absolute;
    width:              100%;
    -webkit-transition: left 0.5s ease-in-out,
                        opacity 0.5s ease-in-out,
                        width 0.5s ease-in-out;
    transition:         left 0.5s ease-in-out,
                        opacity 0.5s ease-in-out,
                        width 0.5s ease-in-out;
}
.mobile #modal.hidden{
    height:             0;
    -webkit-transition: height 0 ease-in-out 0.5s;
    transition:         height 0 ease-in-out 0.5s;
}
.mobile #modal.visible{
    background-color:   #000000;
    height:             100%;
    left:               271px;
    opacity:            0.8;
    right:              0;
    width:              calc(100% - 271px);
    z-index:            99;
}

@MaximillianLaumeister 发表的评论的指导下,我确定问题是没有定义初始高度值。

然后我也尝试转换该值,但最后的解决方案是通过设置 z-index: -1;.

来简单地 "hide" #modal

随着过渡从 99 到 -1(在 0.5 秒内),.mobile #modal 在整个过渡过程中基本可见,仅在结束前约 0.005 秒消失在其他内容后面。

.mobile #modal{
    height:             100%;
    left:               0;
    opacity:            0;
    position:           absolute;
    width:              100%;
    -webkit-transition: all 0.5s ease-in-out;
    transition:         all 0.5s ease-in-out;
    z-index:            -1;
}
.mobile #modal.visible{
    background-color:   #000000;
    height:             100%;
    left:               271px;
    opacity:            0.8;
    right:              0;
    width:              calc(100% - 271px);
    z-index:            99;
}