平滑的CSS向下滑动动画

时间:2018-02-20 20:46:44

标签: javascript jquery html css css-animations

我试图通过点击事件向div添加一个类来平滑下滑动画。

当动画开始然后平衡时,它有点“快速跳跃”,但看起来真的很笨拙,我不知道为什么。

目前正在使用max-height方法将div的高度添加到“打开”,然后再次点击它时,它会切换一个具有max-height:0的类。

如果隐藏的div中有一堆元素应该向下滑动,那么似乎很好,但是如果你只有一个或两个,那么向下滑动动画就会非常激动。想知道我是否需要使用transform:translateY而不是?

这是一个示例链接(Codepen): https://codepen.io/ultraloveninja/pen/ZrxNrj/

var premiumOptions = $(".package-header");
$(premiumOptions).click(handleClick);

function handleClick() {
  console.log("clicked");
  var description = $(this)
    .parent()
    .find(".description");
  if ($(description).length) {
    $(description).toggleClass("open closed");
  }
}
body {
  padding: 20px;
}

.package-item {
  background: #ccc;
  padding: 10px;
}

.closed {
  overflow: hidden;
  max-height: 0;
  padding-top: 0;
  padding-bottom: 0;
  margin-top: 0;
  margin-bottom: 0;
  transition: all 0.5s ease;
  will-change: transform;
}

.open {
  max-height: 1000px;
  overflow: hidden;
  transition: all 0.5s ease;
  will-change: transform;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="package-item line">
  <div class="flex-row package-header">
    <h3>Click This</h3>
  </div>
  <ul class="description closed">
    <li>This is the thing that needs to show smoothly</li>
    <li>This is the thing that needs to show smoothly</li>
  </ul>
</div>

1 个答案:

答案 0 :(得分:2)

您的max-height: 1000px;导致过渡问题,我尝试了低值,看起来很平滑。尝试考虑.open css中的max-height值。

var premiumOptions = $(".package-header");
$(premiumOptions).click(handleClick);

function handleClick() {
  console.log("clicked");
  var description = $(this)
    .parent()
    .find(".description");
  if ($(description).length) {
    $(description).toggleClass("open closed");
  }
}
body {
  padding: 20px;
}

.package-item {
  background: #ccc;
  padding: 10px;
}

.closed {
  overflow: hidden;
  max-height: 0;
  padding-top: 0;
  padding-bottom: 0;
  margin-top: 0;
  margin-bottom: 0;
  transition: all 0.5s ease;
  will-change: transform;
}

.open {
  max-height: 50px;
  overflow: hidden;
  transition: all 0.5s ease;
  will-change: transform;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="package-item line">
  <div class="flex-row package-header">
    <h3>Click This</h3>
  </div>
  <ul class="description closed">
    <li>This is the thing that needs to show smoothly</li>
    <li>This is the thing that needs to show smoothly</li>
  </ul>
</div>