天天看點

移動端學習之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>
           

繼續閱讀