• requestAnimationFrame 兼容方案


    编写涉及:css, html, js

    在线演示codepen

    html代码

    <div class="roll-box">
        <div class="inner-box">move</div>
    </div>
    
    <button onclick="startMove()"> start move</button>
    

    css代码

    .roll-box {
        position: relative;
         600px;
        height: 400px;
        background: #007acc;
        overflow: hidden;
        color: #fff;
    }
    .inner-box {
        position: absolute;
        top: 10px;
        left: 0;
         50px;
        height: 50px;
        text-align: center;
        line-height: 50px;
        background-color: rgb(245, 152, 30);
    }
    button{
        margin-top: 20px;
        padding: 6px 10px;
        border: 0;
        color: #fff;
        background-color: rgb(39, 133, 240);
    }
    

    JavaScript代码

    let moveCount = 0;
    let rafId = '';
    const ele = document.querySelector('.inner-box');
    
    window.requestAniFrame = (function () {
        return window.requestAnimationFrame
    
            // Older versions Chrome/Webkit
            window.webkitRequestAnimationFrame ||
    
            // Firefox < 23
            window.mozRequestAnimationFrame ||
    
            // opera
            window.oRequestAnimationFrame ||
    
            // ie
            window.msRequestAnimationFrame ||
    
            function (callback) {
                return window.setTimeout(callback, 1000 / 60);
            };
    })()
    
    window.cancelAnimation = (function () {
        return window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.cancelRequestAnimationFrame || function (id) { clearTimeout(id) }
    })()
    
    function moveFn() {
        ele.setAttribute('style', 'left:' + moveCount + 'px');
        moveCount++
    
        if (moveCount > 550) {
            window.cancelAnimation(rafId)
        } else {
            rafId = window.requestAniFrame(moveFn)
        }
    }
    
    function startMove() {
        // 必须先清除,否者多次点击会生成多个动画帧,导致元素移动速度加快
        window.cancelAnimation(rafId)
        rafId = window.requestAniFrame(moveFn)
    }
    

    若有疑问或错误,请留言,谢谢!Github blog issues

  • 相关阅读:
    vue中$route和$router的区别
    vscode
    好用的天气插件
    jQuery的slideUp和slideDown函数
    在CSS/JS之后开发工作人员经常会考虑的性能优化。从用户刷新页面,一次js请求下有哪些地方需要缓存
    前端与BI
    XSS和CSRF区别
    兼容性问题
    div跟随鼠标移动
    匀速运动
  • 原文地址:https://www.cnblogs.com/he-wei/p/10297848.html
Copyright © 2020-2023  润新知