will-change

目的:

 让GPU分担CPU的工作,从而优化和分配内存,告知浏览器做好动画的准备。

背景:

 

注意事项:

1,will-change虽然可以加速,但是,一定一定要适度使用;

2,使用伪元素,独立渲染:

  不要这样直接写在默认状态中,因为will-change会一直挂着: 

.a {
  will-change: transform;
  transition: transform 0.3s;
}
.a:hover {
  transform: scale(1.5);
}

  解决方案:

  可以让父元素hover的时候,声明will-change,这样,移出的时候就会自动remove,触发的范围基本上是有效元素范围。

.a-parent:hover .a {
  will-change: transform;
}
.a {
  transition: transform 0.3s;
}
.a:hover {
  transform: scale(1.5);
}

3,如果使用JS添加will-change, 事件或动画完毕,一定要及时remove. 比方说点击某个按钮,其他某个元素进行动画。点击按钮(click),要先按下(mousedown)再抬起才出发。因此,可以mousedown时候打声招呼, 动画结束自带回调,于是:

dom.onmousedown = function() {
    target.style.willChange = 'transform';
};
dom.onclick = function() {
    // target动画哔哩哔哩...
};
target.onanimationend = function() {
    // 动画结束回调,移除will-change
    this.style.willChange = 'auto';
};

 官方:https://developer.mozilla.org/en/docs/Web/CSS/will-change ,给出的示例:

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';
}

 

转载于:https://www.cnblogs.com/wang715100018066/p/7064918.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值