【问题标题】:How to animate a height change using javascript and css?如何使用 javascript 和 css 为高度变化设置动画?
【发布时间】:2015-07-30 01:06:59
【问题描述】:

我有这张点击后会显示的图片,但我希望有一个 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>

【问题讨论】:

  • 我不认为Javascript默认允许动画,你为什么不尝试使用setTimeout来创建效果?

标签: javascript css animation transition


【解决方案1】:

您只需添加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>

【讨论】:

  • 谢谢,我正在尝试transition: all 1s linear 1s;,但你的工作正常
【解决方案2】:

根本没有任何 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 2021-12-08
    • 2016-11-08
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多