will-change
是什么?
在浏览器执行动画之前,提前告诉浏览器,此处需要GPU加速,提高显示效果,但动画结束后要及时去除这个属性
Ie貌似还未支持(有待考证)
添加方法,建议
.will-change:hover{
will-change:transform;
}
也可以使用js进行控制,方法由个人爱好决定;
一下引自MDN
/* Keyword values */
will-change: auto; /* 默认值 */
will-change: scroll-position;
will-change: contents;
will-change: transform; /* Example of <custom-ident> */
will-change: opacity; /* Example of <custom-ident> */
will-change: left, top; /* Example of two <animateable-feature> */
/* Global values */
will-change: inherit;
will-change: initial;
will-change: unset;
Syntax
Values
- This keyword expresses no particular intent; the user agent should apply whatever heuristics and optimizations it normally does.
auto
The <animateable-feature>
can be one of the following values:
- Indicates that the author expects to animate or change the scroll position of the element in the near future.
- Indicates that the author expects to animate or change something about the element’s contents in the near future.
-
Indicates that the author expects to animate or change the property with the given name on the element in the near future. If the property given is a shorthand, it indicates the expectation for all the longhands the shorthand expands to. It cannot be one of the following values:
unset
,initial
,inherit
,will-change
,auto
,scroll-position
, orcontents
. The spec doesn't define the behavior of particular value, but it is common fortransform
to be a compositing layer hint. Chrome currently takes two actions, given particular CSS property idents: establish a new compositing layer or a new stacking context.
scroll-position
contents
<custom-ident>
The above example adds the will-change
property directly to the stylesheet, which will cause the browser to keep the optimization in memory for much longer than it is needed and we've already seen why that should be avoided. Below is another example showing how to apply the will-change
property through scripting, which is probably what you should be doing in most cases.
var el = document.getElementById('element');
// Set will-change when the element is hovered
el.addEventListener('mouseenter', hintBrowser);
el.addEventListener('animationEnd', removeHint);
function hintBrowser() {
// The optimizable properties that are going to change
// in the animation's keyframes block
this.style.willChange = 'transform, opacity';
}
function removeHint() {
this.style.willChange = 'auto';
}
Browser compatibility 浏览器支持
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
Basic support | 36 | 36 (36) [1] | No support | 24 | 9.1 |
[1] From Firefox 31 to 35, will-change
was available, but only if the user flipped the layout.css.will-change.enabled
flag to true
. The preference has been removed in Firefox 43.
Firefox allows to set will-change: will-change
up to version 42.0, which is invalid by the spec. This was fixed in Firefox 43.0. See bug 1195884.