我有一个 ID 为 testimonials
的 div
,height
为 auto
。在 div
中有许多高度不同的 section
。我目前正在运行一个脚本,该脚本一次只显示一个 section
,并为不透明度设置动画。我想找到一个解决方案,允许 #testimonials
在显示新的 section
时为 height
设置动画。
HTML 结构
<div id="testimonials">
<section>
<p>This is the first quote.</p>
</section>
<section>
<p>This is the second quote. It is taller than the previous section.</p>
</section>
<section>
<p>This is the third quote. It is even taller than the previous section two sections.</p>
</section>
</div>
jQuery
(function() {
var testimonials = $("#testimonials section");
var testimonialIndex = -1;
function showNextTestimonial() {
++testimonialIndex;
testimonials.eq(testimonialIndex % testimonials.length)
.fadeIn(2000)
.delay(2000)
.fadeOut(2000, showNextTestimonial);
}
showNextTestimonial();
})();
你可以看到我的CodePen一个工作的例子。
我尝试过的
尝试使用 max-height
因为我没有使用 :hover
,所以不可能为高度设置动画,这似乎是让它工作的唯一方法。我也不能使用 transform: scale()
出于同样的原因,它依赖于 :hover
。我发现的解决方案似乎依赖于 :hover
,仅在 pageload
、window.onresize
、onclick
上触发>,或者当可见的 section
改变时不更新的其他内容。
如何为内容每 6 秒更改一次的 div
设置动画?
最佳答案
使用显示的 section
高度动画化 #testimonials
的高度。
(function() {
var testimonials = $("#testimonials section");
var testimonialIndex = -1;
function showNextTestimonial() {
++testimonialIndex;
var section = testimonials.eq(testimonialIndex % testimonials.length);
section.fadeIn(2000);
$("#testimonials").animate({
height: section.outerHeight(true)
}, 2000);
section.fadeOut(2000, showNextTestimonial);
}
showNextTestimonial();
})();
您可能需要将 overflow: auto
添加到 section 以防止 margin collapse with p inside
section {
display: none;
overflow: auto;
}
关于javascript - 使用不断变化的内容动画化 div 的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42360637/