天天看点

移动端学习之requestAnimationFrame兼容性相关处理

不同厂商兼容性代码:

var raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
        window.setTimeout(callback, 16);
    };
           

调用:

var boxEl = document.getElementById('box'),
        btnEl = document.getElementById('btn');
    var dest = window.innerWidth - 100,
        speed = 1,
        position = 0;
    btnEl.addEventListener('click', function () {
       requestAnimationFrame(step);
    }, false);

    function move(ele, position) {
        ele.style.transform = 'translate3d(' + position + 'px,0,0)';
    }
    function step() {
        if (position<dest){
            position+=speed;
            move(boxEl,position);
            requestAnimationFrame(step)
        }else {
            position=dest;
            move(boxEl,position)
        }
    }
           

html结构

<style>
        * {
            margin: 0;
            padding: 0;
        }
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>
<body>
<button id="btn">start</button>
<div id="box" class="box"></div>
</body>
           

继续阅读