gpt4 book ai didi

css - 如何使用 CSS 的 will-change 属性?

转载 作者:数据小太阳 更新时间:2023-10-29 09:10:45 24 4
gpt4 key购买 nike

我发现 CSS will-change W3.org docs , MDN docs 属性(它已经在 Chrome 中工作,并且在 Firefox 和 Opera 中得到部分支持)但我不太确定它是如何工作的。有人知道更多关于这个神秘事物的信息吗?

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

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

    .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);
    }
  2. 它如何提高浏览器性能?理论上,当加载 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.

使用方法:

will-change: transform, opacity;

如何不使用它:

will-change: all;

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

在悬停时指定 will-change 无效:

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 - 如何使用 CSS 的 will-change 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26907265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com