css vs js动画及requestAnimationFrame优化动画

transition

transition存在的问题:

  • 只能设置动画的起始状态,不能设置中间状态
  • 必须明确开始状态和结束状态的具体值,不能识别0到auto,none到block,background中URL的变化
  • 必须触发才执行,且只执行1此
  • IE10以上已经不需要ms前缀
  • 对某些参数不起作用,如index
.trans {
    transition: all 0.3s ease;
}
.trans:hover {
    background-color: #486AAA;
    color: #fff;
}

transition参数介绍

  • transition-property :* //指定过渡的性质,比如transition-property:backgrond 就是指backgound参与这个过渡

  • transition-duration:*//指定这个过渡的持续时间

  • transition-delay:* //延迟过渡时间

  • transition-timing-function:*//指定过渡类型,有ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier,其中,ease-in表示先快后慢。ease-in-out表示先快后慢再快。

transform加上transition一起使用效果更佳

.trans_effect {
    transition:all 2s ease-in-out;
}
.trans_effect:hover {
    transform:rotate(720deg) scale(2,2);        
}
还有属性transformskew(倾斜),translate

animation

animation解决了transition存在的问题

@-webkit-keyframes resize {
    0% {
        padding: 0;
    }
    50% {
        padding: 0 20px;
        background-color:rgba(190, 206, 235, 0.2);        
    }
    100% {
        padding: 0 100px;
        background-color:rgba(190, 206, 235, 0.9);
    }
}
.anim_box:hover {
    -webkit-animation-name: resize;
    -webkit-animation-duration: 1.5s;
    -webkit-animation-iteration-count: 4;
    -webkit-animation-direction: alternate;
    -webkit-animation-timing-function: ease-in-out;
}

css控制动画优势

  1. 实现简单动画容易且代码量少
  2. 浏览器使用类似requestAnimationFrame的机制优化动画

js操作动画优势

  1. 容易控制,比如在两个动画之间执行其他操作,且能添加回调函数
  2. 基本无兼容性问题
  3. 能用requestAnimationFrame将动画集中在浏览器下次刷新页面时执行

js操作动画缺点

  1. js在浏览器主线程中运行,若主线程中还要运行其他脚本,则可能造成丢帧的情况
  2. 复杂度高

css动画比js动画流畅的前提

  1. js在执行费时的操作
  2. css不出发reflow

下面属性不会触发reflow

  • opacity
  • transform
  • backface-visiblity
  • perspective
  • perspective-origin

requestAnimationFrame使用举例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        #ele{
            width:100px;
            height:100px;
            background-color: #00b3ee;
        }
    </style>
</head>
<body>
<div id="ele"></div>
<script type="text/javascript">
    var ele = document.getElementById('ele');
    function changeSquare() {
        ele.style.width = parseInt(getComputedStyle(ele).width)+1+'px';
        ele.style.height = parseInt(getComputedStyle(ele).width)+1+'px';
    }
    (function start() {
        changeSquare();
        if(ele.offsetWidth < 400){
            requestAnimationFrame(start);
        }
    })();
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值