高度转换无法使用javascript工作

时间:2015-06-28 09:36:36

标签: javascript css3

我正在尝试使用转换来折叠DIV,只是它没有工作,我不知道如何使用javascript工作。当我按下指定按钮时,div会立即崩溃,而不是超过2秒。我正在使用chrome。

div的CSS:

 .new_dynDiv {
text-align: left;
background-color: white;
padding: 5px;
margin-top: 10px;
margin-bottom: 10px;

}

我的Javascript用于在按下按钮时使用转换折叠div:

 var div_article = document.getElementById('new_dynDiv_'+id);
                                div_article.style.height = '0px';
                                div_article.style.transition= 'height 2s';

我也尝试了以下尝试,但转换仍未奏效:

 .new_dynDiv_fade{
height: 0px;
transition: height 2s;

}

上述过渡的javascript代码:

 var div_article = document.getElementById('new_dynDiv_'+id);
div_article.className = 'new_dynDiv_fade';

1 个答案:

答案 0 :(得分:1)

您至少有两种方法可以实现您的目标:

  • 使用CSS动画
  • 使用jQuery动画

我用CSS动画创建了一个简单的例子。希望它可以帮到你。

<style>
    .new_dynDiv {
        text-align: left;
        background-color: white;
        padding: 5px;
        margin-top: 10px;
        margin-bottom: 10px;

        height: 100px; /* the initial height needed for the animation to work*/
        transition: height 2s; /* the animation for the height property */
        overflow: hidden; /* hide the content of the element when collapsed */
    }

    .new_dynDiv.collapsed {
        height: 0px;
    }
</style>

<div class="new_dynDiv" id="new_dynDiv_1">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

<button id="btnCollapse" onclick="toggleCollapsed(1); return false;">Collapse</button>

<script>
    function toggleCollapsed(id) {
        var div_article = document.getElementById('new_dynDiv_' + id);
        div_article.classList.toggle("collapsed");
    }
</script>