【问题标题】:How to animate div height with web-animations-js?如何使用 web-animations-js 为 div 高度设置动画?
【发布时间】:2019-10-26 07:40:50
【问题描述】:

如何使用web-animations-js 为 div 高度设置动画?

在我的示例中,我尝试将高度大小从 150 像素更改为 300 像素。但我想为高度设置动画。我不能用 css 做到这一点,因为高度是可以改变的(例如从 90px 到 500px)。

如何使用 web-animation-js 解决这个问题?

var elem = document.querySelector('.some');
  
  var animation = elem.animate({
   height: '300px'
  }, {
   duration: 500
  });

  console.log('done');
.some {
  width:300px;
  height:150px;
  border:1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.2/web-animations.min.js"></script>
<div class="some"></div>

【问题讨论】:

  • 为什么在 css 中不可能?添加一个具有新高度的类,在这个类上放置一个动画,然后将该类应用到您的元素:)
  • 你为什么不使用 CSS ? Css Transform 可以帮助你。
  • 因为高度是由 JavaScript 决定的。例如,我决定当您单击时,高度为 500 像素。
  • 如何计算 div 的高度?
  • 高度是一个随机数..

标签: javascript html css


【解决方案1】:

您可以使用速度来做到这一点。 (使用javascript)

示例如下:

document.querySelector('.some').velocity({ height: 300 });
.some {
  width:300px;
  height:150px;
  border:1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/2.0.5/velocity.min.js" integrity="sha256-NtPQd/Jy7Ze2E72YS8WJDGMu6xFYomLYibE0hpyLTjs=" crossorigin="anonymous"></script>

<div class="some"></div>

【讨论】:

    【解决方案2】:
    let el = document.querySelector(".some");
    
    el.style.transition = "all 2s ease-in-out 0s";
    
    let randomHeight= ... ;
    
    el.style.height = randomHeight+"px";
    

    你得到一个高度值“randomHeight”然后这将改变元素的高度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多