【问题标题】:CSS3 animation on max-height not working as expected最大高度上的 CSS3 动画未按预期工作
【发布时间】:2023-12-24 08:08:01
【问题描述】:

我正在尝试在应用类后为元素的高度设置动画,这是简化的代码:

HTML

<div class="section">
  <div class="panel">
    <a href="#" class="toggle">Click</a>
    <div class="panel-content">
      Some content...
    </div>
  </div>
</div>

CSS

.section {
  position: relative;
  width: 500px;
  height: 200px;
  margin: 100px auto;
  background: #ccc;
}

.panel {
  width: 65%;
  position: absolute;
  left: 0;
  bottom: 0;
}

.toggle {
  display: inline-block;
  height: 15px;
  background: #ddd;
}

.panel-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 1s;
}

.active .panel-content {
  max-height: 9999px;
}

JS

$(function() {
  $('.toggle').on('click', function (e) {
    e.preventDefault();
    $(this).closest('.panel').toggleClass('active');
  });
});

当我点击.toggle 链接时,.panel 元素上设置了一个active 类来为.panel-content 高度设置动画,但是当第一次添加该类时,显示的内容没有动画,当它被删除时元素需要一秒钟(过渡的持续时间)开始动画。你可以在这里看到一个现场演示:http://codepen.io/javiervd/pen/bLhBa

我也尝试过使用 position 和 overflow 属性,但我无法让它发挥作用,也许还有另一种方法可以达到同样的效果?

提前致谢。

【问题讨论】:

    标签: css height css-transitions animated


    【解决方案1】:

    当有事情发生时,您需要发送transition。这不是你想要的,但让我告诉你一些东西:

    .pannel-content{
      height:0;
    }
    .pannel-content:hover{
      height:50px; transition:height 2s;
    }
    

    这就是transition 的工作原理。您尚未创建操作。没有 click Pseudo Class,无论如何您都不想影响相同的元素。尝试使用 jQuery 之类的。

    <html>
      <head>
        <style type='text/css'>
          .active .pannel-content{
            display:none; height:9999px;
          }
        </style>
      </head>
    <body>
      <div class='section'>
        <div class='panel'>
          <a href='#' class='toggle'>Click</a>
          <div class='panel-content'>
            Some content...
          </div>
         </div>
      </div>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
      <script type='text/javascript'>
        $('.toggle').click(function(){
          $('.active .pannel-content').show('slow');
        });
      </script>
    </body>
    </html>
    

    您也可以使用 jQuery 的 .animate() 方法。当然,我建议您使用 declair 一个 DOCTYPE 并使用 &lt;meta&gt; 标签。此外,您应该使用外部 CSS,因为它会缓存在您的用户浏览器内存中。
    详情请访问http://api.jquery.com/show/http://api.jquery.com/animate/

    【讨论】:

    • 我确实将活动类添加到我的.panel 元素中以使转换发生我只是为了简洁而省略了,但它在我发布的代码笔上,不过我会用 javascript 更新我的答案。