css 过渡动画问题

JS Bin链接: https://jsbin.com/hofoconeru/...

如图, 当p标签被显示出来时会把box高度撑起来,为什么满足不了 transition all .5s 这个动画?

我想要的效果是当box的高度发生变化时添加过渡动画,不想一下就撑高,要慢慢高那种效果,请问该怎么实现?

阅读 1.9k
3 个回答

css 动画不支持 height: auto,可以用 js 获取 .box 实际高度,点击按钮切换高度:

css

.box {
  background-color: blue;
  overflow: hidden;
  transition: all 1s;
}

js

const autoH = $('.box').height();
let h = 0;
$('.box').height(0);
$('.button').click(function() {
  $('.box').height(h ^= autoH);
});

这里你除了使用 height 还可以使用 max-height ,先给 max-height 设置 0,然后在 active 时,给 max-height 设置一个较大的值即可。

另外,对于你这种,判断 class 是否存在在进行添加/移除的操作,在 jQuery 中,还可以使用 toggleClass,在原生 JS 中 也可以使用 classList 的 toggle 方法。

<style>
    .box {
        max-height: 0;
        overflow: hidden;
        transition: max-height .3s linear;
    }

    .box.active {
        max-height: 999px;
    }
</style>
<div class="button">切换1</div>
<div class="button2">切换2</div>
<div class="box">
    <p>第1行</p>
    <p>第2行</p>
    <p>第3行</p>
    <p>第4行</p>
    <p>第5行</p>
    <p>第6行</p>
    <p>第7行</p>
    <p>第8行</p>
    <p>第9行</p>
    <p>第10行</p>
</div>
<script src="https://lib.baomitu.com/jquery/latest/jquery.slim.min.js"></script>
<script>
  $('.button').on('click', function () {
    $('.box').toggleClass('active')
  })

  document.querySelector('.button2').addEventListener('click', function () {
    document.querySelector('.box').classList.toggle('active')
  })
</script>

https://developer.mozilla.org...

auto 值常常较复杂,规范指出不要在它上动画。一些用户代理,比如基于 Gecko 的,遵循这点;一些,比如基于 WebKit 的,没有这么严格限制。在 auto 上动画结果可能不可预期,这取决于浏览器及其版本,应当避免使用。
同时应当留意这种情形,在插入元素(如 .appendChild())或改变属性 display: none 后立即使用过渡,元素将视为没有开始状态,始终处于结束状态。简单的解决办法,改变属性前用 window.setTimeout() 延迟几毫秒。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题