使用javascript/jQuery添加类时,为什么css过渡不起作用?

Ste*_*ven 5 javascript jquery css-transitions angularjs

我有一个消息框,我想在点击时向下滑动.我通过Angular添加一个css类(在我的例子中使用jQuery)来实现这一点.但是我的CSS转换没有生效.

我在做什么明显的错误?

这是我的小提琴:http://jsfiddle.net/mBKXn/

和我的代码:

// jQuery
$('.test').on('click',function(){
  $('#msgContainer').toggleClass('msgShow');
});

// HTML
<div class="container">
    <div id="msgContainer" class="msg">
        <p>Message here</p>
        <p>T2</p>
        <p>T4</p>
    </div>
    Test text
</div>

<button class="test">Click</button>

// CSS
.container{
    position: relative;
    height: 200px;
    width: 400px;
    border: solid 1px #222;
}

.msg{
    position: absolute;
    top: 0;
    background-color: #FEEFB3;
    height: 0;
    width: 100%;
    overflow: hidden;
    -webkit-transition: height 0.8s linear;
    -moz-transition: height 0.8s linear;
    -o-transition: height 0.8s linear;
    -ms-transition: height 0.8s linear;
    transition: height 0.8s linear;    
}

.msgShow{
    height: auto;
}
Run Code Online (Sandbox Code Playgroud)

kas*_*ans 6

您需要设置一个定义的高度。Height:auto 不起作用,因为这是默认高度值。

请参阅此处 height 属性的规格: http://www.w3.org/TR/CSS2/visudet.html#the-height-property

http://jsfiddle.net/mBKXn/7/

.msgShow{
    height: 100%;
}
Run Code Online (Sandbox Code Playgroud)


dfs*_*fsq 6

要将高度从0设置为自动,您必须使用max-height:

.msg{
    position: absolute;
    top: 0;
    background-color: #FEEFB3;
    max-height: 0;
    width: 100%;
    overflow: hidden;
    -webkit-transition: max-height 0.8s linear;
    -moz-transition: max-height 0.8s linear;
    -o-transition: max-height 0.8s linear;
    -ms-transition: max-height 0.8s linear;
    transition: max-height 0.8s linear;    
}

.msgShow{
    max-height: 1000px;
}
Run Code Online (Sandbox Code Playgroud)

似乎工作:http://jsfiddle.net/mBKXn/3/

另外看看这个问题.

  • 这确实有效,但这是有问题的,因为一旦max-height值超过高度,即使浏览器继续"动画化",也没有进一步的*视觉*改变.当您再次单击时,会有一个明显的暂停,同时该值将*向下*设置为实际高度. (4认同)