max-height上的CSS3动画未按预期工作

时间:2013-06-22 20:47:05

标签: css css3 height css-transitions animated

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

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链接时,active元素上设置了.panel类来设置.panel-content高度的动画,但是当首次添加该类时,内容为显示没有动画,当它被删除时,元素需要一秒钟(转换的持续时间)来开始动画。您可以在此处查看实时演示:http://codepen.io/javiervd/pen/bLhBa

我尝试使用位置和溢出属性,但我无法使其工作,也许还有另一种方法可以实现相同的效果?

提前致谢。

1 个答案:

答案 0 :(得分:1)

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

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

这就是transition的工作原理。您尚未创建操作。没有单击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()方法。当然我建议你使用声明DOCTYPE并使用<meta>标签。此外,您应该使用外部CSS,因为它将缓存在您的用户浏览器内存中 有关详细信息,请访问http://api.jquery.com/show/http://api.jquery.com/animate/

相关问题