我试图通过向带有点击事件的 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>
最佳答案
您的 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>
关于javascript - 流畅的 CSS 向下滑动动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48893936/