javascript - 如何使用 jQuery 在 html() 函数之后为元素的高度设置动画?

标签 javascript jquery html css

我的元素几乎准备就绪,我想做的最后一件事是为 .quote-container 元素的高度设置动画。目前,它变化非常快,没有任何动画效果,不幸的是,这行 CSS 不起作用:

.quote-container {
  transition: height 1s;
}

但是,同一行仅适用于 #new-quote 选择器,有效:

#new-quote {
  transition: height 1s;
}
看笔gomeYN卢卡斯 ( @Kestis500 ) 在 CodePen .


我制作了一个视频,以便您理解我的意思: https://www.youtube.com/watch?v=21V3NbAagnk&feature=youtu.be .

此外,在 0:08 - 0:09 秒内,.quote-container 元素的高度变化出现错误。这里发生了什么?

我查看了 jQuery 文档中的 animate() 函数,但我不明白如果 .quote-container 中的文本发生变化如何实现它每次按下 #new-quote 按钮时。


这不是一个与 this one 完全相同的问题.我已经完成了该问题的答案中所写的内容,但它仍然无法正常工作。另外它使用的是 CSS,而不是 JS。我保存了我的代码笔:https://codepen.io/Kestis500/pen/gomeYN?editors=0100 .有人可以看看并说出我做错了什么吗?这是我的更改:

//CSS
.quote-container, #new-quote { transition: max-height 1s; }

//JS
$("#new-quote").on("click", function() {
  $(".quote-container").css({ maxHeight: 0, overflow: "hidden" });
  $(".quote-text, .quote-author").fadeTo(1000, 0, function() {
    getQuote(function() {
      $(".quote-container, #new-quote").css({
        maxHeight: $(".quote-container").outerHeight()
      });
      $(".quote-text, .quote-author").fadeTo(1000, 1);
    });
  });
});

编辑 1 我已经更改了我的代码,因此当页面加载时,它会平滑地更改最大高度,从而产生我需要的流畅动画。代码笔:https://codepen.io/Kestis500/pen/WdpBqv?editors=0010 ,但是,我仍在处理点击事件,因为它的工作方式与页面加载不同。

编辑 2 谢谢 Twisty 的大力帮助 :) 我对自己的偏好做了一些更改,现在唯一需要修复的是动画应该同时开始(#new-quote.quote-container 元素),但是,我认为它会很容易修复 :)

编辑 3 开始了!正是我所需要的,而且动画很棒! :) https://jsfiddle.net/z5hds4Lp/ .

编辑 4 https://jsfiddle.net/z5hds4Lp/2/ - 最终编辑。

注意:不要在媒体查询或 CSS 中使用像素,对 CSS 使用 rems,对媒体查询使用 ems: https://engageinteractive.co.uk/blog/em-vs-rem-vs-pxhttps://zellwk.com/blog/media-query-units/ .

最佳答案

要使用 .animate() 更改元素的高度,您必须设置像素值。

例子:

$(function() {
  $("#clickme").click(function() {
    $("#book").animate({
      opacity: 1,
      height: 123
    }, 1000, function() {
      // Animation complete.
    });
  });
});
#book {
  width: 20px;
  height: 30px;
  border: 1px solid black;
  background-color: #CCC;
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
  Click here
</div>
<div id="book"></div>

您可以调整很多 CSS 属性。大多数只会取整数。有些人会采取替代方案。

In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'. These shortcuts allow for custom hiding and showing animations that take into account the display type of the element. In order to use jQuery's built-in toggle state tracking, the 'toggle' keyword must be consistently given as the value of the property being animated.

Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

对于您的代码,您可以考虑类似(代码段)的内容:

$("#new-quote").on("click", function() {
  $(".quote-text, .quote-author").fadeTo(1000, 0, function() {
    getQuote(function() {
      $("#new-quote").animate({
        height: $(".quote-container").outerHeight(),
        opacity: 1
      }, 1000);
    });
  });
});

getQuote(function() {
  $("#new-quote").animate({
    height: $(".quote-container").outerHeight(),
    opacity: 1
  }, 500);
});

工作:https://jsfiddle.net/k24ykxeb/2/

希望这对您有所帮助。

更新 1

添加了一些日志记录,包括计时,我看到了:

Start. 0
Ready. 14
Animate body, .button:not(#new-quote) Background. 19
Animate Text Color Change. 29
Updating Text Color. 31
Appending  to Head. 32
JSON Callback Started. 888
Running Callback Function. 890
Start Resize Animation. Target Outer Height: 222; 893
JSON Callback Complete. 898
Completed Resize Animation, new height: 222, opacity: 1, after 500ms 1405
Completed Resize Animation, new height: 222, opacity: 1, after 500ms 1406

Working Example: https://jsfiddle.net/k24ykxeb/7/

Whats interesting here is that I am see the animation appear to complete twice. Events seem to be executing as intended. I was concerned that the resize was triggering before the Quote and title were appended. Does not appear to be the case.

Still investigating.

Update 2

Found that the padding for #new-quote was being defined by the .button class and did not match the .quote-container. I adjuste it to the following:

padding: 2.5rem 0.75rem;

这解决了剩下的 40 像素的差距。这在工作示例中可以在这里看到:https://jsfiddle.net/k24ykxeb/9/

另一种选择是使 .quote-container 在其中包含 #new-quote。这将允许它与父级一起回流。

克隆技术适用于 Ajax 调用,在这种情况下您不知道会有多少文本,因此在将文本放入 div 之前您无法计算新的高度。如果拉取文本,克隆 div,将文本添加到克隆中,则可以获得 height 属性。然后放下克隆,调整容器大小并淡入文本。

更新 3

很多东西都在运动,必须在特定时间启动才能使动画正常工作。输入 .queue()

示例:https://jsfiddle.net/k24ykxeb/26/

jQuery 片段

var getQuote = function(e) {
  /***
  Steps
  1) Fade Text Out
  2) Bounce expansion effect
  3) Change color
  4) Animate to new size
  5) Fade New Text In
  ***/

  var nq, nc, nh = 0;

  $(".quote-container").queue(function() {
      // 1) Fade out text
      console.log("Step 1", Date.now() - start);
      $(".quote-container").children().animate({
        opacity: 0
      }, 750);
      $(this).dequeue();
    })
    .queue(function() {
      console.log("Step 3", Date.now() - start);
      nq = getNewQuote();
      nc = getRandomColor();
      // 3) Change Color
      changeColor(nc);
      $(this).dequeue();
    })
    .queue(function() {
      console.log("Step 4", Date.now() - start);
      // 4) Animate to new size
      nh = calcNewHeight(nq);
      $(".quote-container, #new-quote").animate({
        height: nh
      }, 1000);
      $(this).dequeue();
    })
    .queue(function() {
      console.log("Step 5", Date.now() - start);
      // 5) Fade in new text
      updateText($(".quote-container"), nq);
      $(".quote-container").children().fadeTo(750, 1);
      $(this).dequeue();
    })
};

$(function() {
  console.log("Ready.", Date.now() - start);
  $("#new-quote").on("click", getQuote);
  getQuote();
});

$.getJSON() 也是异步执行的,所以我切换到 $.ajax() 以获得 async: false 的好处.

关于javascript - 如何使用 jQuery 在 html() 函数之后为元素的高度设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48010957/

相关文章:

javascript - 维基百科 API - 访问 JSON 对象

javascript - Function.prototype.bind.apply 意思没看懂

javascript - Angular - 数据更新后运行 jQuery

Javascript - 在 Ajax 中使用确认感到困惑

html - CSS 交叉淡入淡出动画

html - Bootstrap 中心下拉菜单

javascript - 将 jQuery 创建的元素附加到 vanilla js?

javascript - 我什么时候应该使用批处理并最终关闭 pg-promise 中的客户端连接?

javascript - 如何使用 underscore.js 或 jquery 删除模式

html - 如何让 child 不向 parent 展示?