1

根据谷歌:

一般的经验法则是,如果动画可能在接下来的 200 毫秒内触发[...] ,那么对动画元素进行 will-change 是个好主意。因此,在大多数情况下,您打算在应用程序当前视图中设置动画的任何元素都应该为您计划更改的任何属性启用 will-change。

所以我的问题是,可以will-change在任何属性实际动画之前通过 Web Animations API 应用,这会产生预期的效果吗?或者在幕后发生的任何事情的生命周期中为时已晚,will-change无法正常工作?

似乎通过这个 API 修改的属性实际上并没有作为 CSS 属性反映在 DevTools 中,所以我无法验证这是否真的应用will-change了。

想法的例子:

this.animation = document.querySelector('#my-element').animate(
  [
    {
      willChange: 'opacity', // will-change applied before any animated property has been changed
      opacity: 'initial',
    },
    {
      willChange: 'opacity',
      opacity: 'initial',
      offset: 0.01, // 1% of the way through the animation
    },
    {
      willChange: 'opacity',
      opacity: 0.5,
      offset: 0.5, // 50% of the way through the animation
    },
    { 
      willChange: 'initial',
      opacity: 'initial'
    },
  ],
  1000
);
4

2 回答 2

2

是的,它会产生预期的效果。

动画会影响元素的计算样式,但许多 DevTools 面板会呈现元素的指定样式,因此您看不到它的原因。

另一种方法是简单地为动画添加一个短暂的延迟。在动画的延迟阶段,浏览器需要应用will-change: opacity(或任何其他正在动画的属性)。(规格参考

That said, there is really no advantage to doing so. The purpose of applying will-change is to let the browser prepare the content for animating (e.g. by re-rasterizing it as separate layers) so that the animation starts without delay. If you simply start the animation as normal, the browser will re-rasterize as necessary and then begin the animation from the start.

The advantage to using will-change is if you know before you need to start the animation which element you are going to animate, you can let the browser doing that preparation ahead of time.

于 2020-11-01T23:14:35.427 回答
-2

It looks like will-change is actually completely unnecessary when using WAAPI (Web Animation API.)


if you have a delay on your animation, you don’t need to worry about using will-change. -- Source

From one of the authors of the spec:

If you have a positive delay, you don’t need will-change since the browser will layerize at the start of the delay and when the animation starts it will be ready to go.

于 2020-11-04T22:17:19.567 回答