如何使用 javascript 和 css 为高度变化设置动画?

How to animate a height change using javascript and css?

我有这张图片,点击时会显示出来,但我希望有 1 秒左右的过渡动画。

我不想使用 jQuery。适合移动设备的 css 解决方案会很棒。

有什么想法吗?

#cover {
  height: 100px;
  overflow: hidden;
  border-radius: 4px 4px 0 0;
}
#image {
  width: 100%;
  display: block;
}
<div class="cover" id="cover">
  <img src="http://lorempixel.com/500/500/cats/" onclick="myFunction()" id="image" />
</div>
<script>
  var isOpen = false;

  function myFunction() {
    var image = document.getElementById('image');
    var cover = document.getElementById('cover');
    if (isOpen === false) {
      cover.setAttribute("style", "height:" + image.offsetHeight + "px");
      isOpen = true;
    } else if (isOpen !== false) {
      cover.setAttribute("style", "height:100px");
      isOpen = false;
    }
  }
</script>

您只需添加 transition: height 1s 即可获得一秒的动画:

#cover {
  height: 100px;
  overflow: hidden;
  border-radius: 4px 4px 0 0;
  -webkit-transition: height 1s; 
  -moz-transition: height 1s; 
  -ms-transition: height 1s; 
  -o-transition: height 1s; 
  transition: height 1s;  
}
#image {
  width: 100%;
  display: block;

}
<div class="cover" id="cover">
  <img src="http://lorempixel.com/500/500/cats/" onclick="myFunction()" id="image" />
</div>
<script>
  var isOpen = false;

  function myFunction() {
    var image = document.getElementById('image');
    var cover = document.getElementById('cover');
    if (isOpen === false) {
      cover.setAttribute("style", "height:" + image.offsetHeight + "px");
      isOpen = true;
    } else if (isOpen !== false) {
      cover.setAttribute("style", "height:100px");
      isOpen = false;
    }
  }
</script>

有一种不使用任何 JS 的 hacky 方法。我使用了 max-height 属性,这样它可以用于没有固定高度的图像。

#cover {
    min-height:100px;
    max-height:100px;
    overflow:hidden;
    position:relative;
    transition: all linear 1s;
}

#coverToggle:checked + #cover {
    max-height:500px;
}

label {
    position:absolute;
    left:0px;
    top:0px;
    right:0px;
    bottom:0px;
}

input {
    position:absolute;
    visibility:hidden;
    top:-100px;
    left:-100px;
}
<input type="checkbox" id="coverToggle" />
<div class="cover" id="cover">
    <label for="coverToggle"></label>
    <img src="http://lorempixel.com/500/500/cats/" id="image" />
</div>