在 Dart 2 中为 HTML 元素创建类似 jQuery 的动画

Creating jQuery-like animations in Dart 2 for a HTML element

如何在 Dart 2 中为类似于 jQuery fadeInfadeOut 的 HTML 元素创建动画?

我在dart:html包里看到了这个animate方法。但是,它似乎并没有将元素的样式更改为最终状态,因此在动画完成后,元素立即像动画开始之前一样变回第一个状态。文档还指出,调用 animate 不仅会创建 Animation class,还会调用 play() 方法,因此动画会在创建时自动播放。

dart:html 包中的 animate 是否使用 Web Animation,所以它根本不会改变 HTML 元素的样式?如果是这样,我如何在动画完成后保持元素的状态?我可以看到使用 jQuery fadeIn 元素的不透明度不时从 0 变为最终状态 1。因此在动画完成后,元素的不透明度保持为 1。

我希望我能避免这种情况:

elem.animate([{"opacity": 1}, {"opacity": 0}], 100); // animation is played immediately after this
elem.style.opacity = "0"; // force set the style to 0
elem.style.display = "none"; // also force set the display to none

Dart 的动画 API 直接移植 Web Animations API so anything you can do with it, you can do in Dart in almost exactly the same way. With WAAPI, creating animations always involves two parts: specifying the keyframes (a.k.a. the effect) and then timing parameters(或者只是持续时间,如果不需要特定的计时效果)。

在计时参数中,有一个称为 fill mode 的参数,它会影响当动画未激活时元素​​的呈现方式 运行ning。要让元素在动画结束后保持在动画结束时定义的状态,您需要做的就是将 fill 参数设置为 forwards.

就像Javascript中的WAAPI一样,在Dart中,动画时间参数是在animate方法的第二个参数中设置的,用一个Map来代替duration。这也是您设置延迟、缓动和动画方向等内容的地方。

//Notice that this Dart code is entirely compatible with JS!
el.animate([{"opacity": 0}], {
  "duration": 1000,
  "fill": "forwards"
});

Here's a working example.

您还可以在元素之前构建动画运行。 .animate 方法 returns 一个 Animation 对象,您可以从中存储和控制动画。您可以创建它,立即对其调用 .pause,然后稍后播放,等等。这仍然与 WAAPI 完全持平。

Animation fadeOutEl = el.animate([{"opacity": 0}], {
  "duration": 1000,
  "fill": "forwards"
})..pause();
// Somewhere else 
fadeOutEl.play();

Dart 的动画文档 API 肯定很少,但是由于它实际上与 WAAPI 相同(毕竟它是建立在它之上的),您需要做的就是看看它MDN 上的文档,从那里,转换为 Dart 的实现非常简单。