javascript - 使用不断变化的内容动画化 div 的高度?

标签 javascript jquery css

我有一个 ID 为 testimonialsdivheightauto 。在 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,仅在 pageloadwindow.onresizeonclick 上触发>,或者当可见的 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/

相关文章:

javascript - 如何使用expressJS处理Fetch api formData提交

jquery:选择元素的 css left:position 大于 left:position 的所有同级元素

javascript - 有没有一种方法可以通过单击按钮来验证表单的一部分,而无需先实际提交表单?

css - WordPress CSS 和内联 SVG

html - 如何从嵌套在 Div 中的无序列表中删除元素符号?

html - 旋转 iPhone 5 时网页缩放

javascript - 如何在不同操作系统上使用源映射文件

javascript - play 2.2 webjars requirejs jquery 集成

javascript - 带条件的 ng-options 中的默认值

javascript - 具有相同 ID 的多个 div 的事件