CSS`will-change` – 如何使用它,它是如何工作的

前端之家收集整理的这篇文章主要介绍了CSS`will-change` – 如何使用它,它是如何工作的前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我发现CSS will-change W3.org docsMDN docs属性(它已经在Chrome中工作,并且被Firefox和Opera支持),但我并不确定它是如何工作的。
有谁知道这个神秘的东西吗?

我刚刚读到它允许浏览器准备在将来的元素上进行计算。
我不想误会。所以我有几个问题。

>我应该将此属性添加到元素类或其悬停状态吗?

.my-class{
    will-change: 'opacity,transform'
}
.my-class:hover{
    opacity: 0.5
}
.my-class:active{
    transform: rotate(5deg);
}

要么

.my-class{
    ...
}
.my-class:hover{
    will-change: 'opacity'
    opacity: 0.5
}
.my-class:active{
    will-change: 'transform'
    transform: rotate(5deg);
}

>如何增加浏览器的性能?理论上,当CSS被加载时,浏览器已经“知道”每个元素会发生什么,不是吗?

如果你可以添加任何很好的例子说明如何有效地使用它,我会感激的:)

解决方法

我不会复制粘贴整个 article在这里,但这里是一个tl; dr版本:

Specifying what exactly you want to change allows the browser to make better decisions about the optimizations that it needs to make for these particular changes. This is obvIoUsly a better way to achieve a speed boost without resorting to hacks and forcing the browser into layer creations that may or may not be necessary or useful.

如何使用它:Da

will-change: transform,opacity;

如何使用它:

will-change: all;

.potato:hover {
  will-change: opacity;
  opacity:1;
}

在悬停上指定意志变化无效:

Setting will-change on an element immediately before it changes has little to no effect. (It might actually be worse than not setting it at all. You could incur the cost of a new layer when what you’re animating wouldn’t have prevIoUsly qualified for a new layer!)

猜你在找的CSS相关文章