内容更改时的动画高度css3

时间:2014-11-06 10:25:41

标签: javascript html css3

有没有办法在内容更改时(通过脚本和\或css)动画div的高度?

div {
  width:100px;
  }

#b {
  display:none;
  }

.wrapper.switch #a {
  display:none;
  }

.wrapper.switch #b {
  display:block;
  }
<div class="wrapper">
  <div id="a">
    Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text 
    </div>
  <div id="b">
    Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text 
    </div>
  
  <button onclick="document.querySelector('.wrapper').classList.toggle('switch');">swich</button>

1 个答案:

答案 0 :(得分:0)

我认为这个脚本可以帮到你:

<html lang="en">
<head>
<meta charset="UTF-8">
<title>stackoverflow</title>
<style type="text/css">
    .box{
        width: 350px;
        padding:20px;
        border: 1px solid #ccc;

    }
  .box p{
        margin: 0;
        padding-top: 20px;
    }
    .box p:first-child{
        padding-top: 0;
    }

</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    // Defining the function
    function animateHeight(){
        var newHeight = $(".box-inner").height();
        $(".box").animate({
            height: newHeight,
        }, 500);
    }
    $(".load-more").click(function(){
        // Setting the initial height of the box
        $(".box").height($(".box-inner").height());

        // Appending box with new content and animate the height
        var newContent = "<p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text</p>";
        $(".box-inner").append(newContent);
        animateHeight();
    });
});
</script>
</head>
<body>
<button class="load-more">Switch</button>
<p>Height Changes Whenever you click</p>
<div class="box">
    <div class="box-inner">
        <p>Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text
        </p>
    </div>
</div>
</body>
</html>