【问题标题】:requestAnimationFrame not working in EdgerequestAnimationFrame 在 Edge 中不起作用
【发布时间】:2018-09-26 05:42:24
【问题描述】:

我正在尝试添加一个在所有浏览器上都能正常运行的平滑滚动(但只有 IE11 和 Microsoft 的 Edge)。问题是这个脚本完全破坏了 Edge 浏览器中的滚动。

我已包含控制台日志,确认脚本正在计算鼠标滚轮的移动,但是页面没有“视觉”移动。

new SmoothScroll(document, 120, 12);
function SmoothScroll(target, speed, smooth) {
if (target == document) {
    target = document.documentElement || document.body.parentNode || document.body; // cross browser support for document scrolling
    var moving = false;
    var pos = window.pageYOffset;
    target.addEventListener("mousewheel", scrolled, false);
    target.addEventListener("DOMMouseScroll", scrolled, false);
}

function scrolled(e) {
    e.preventDefault(); // disable default scrolling
    var delta = e.delta || e.wheelDelta;

    if (delta === undefined) {
        //we are on firefox
        delta = -e.detail;
    }

    delta = Math.max(-1, Math.min(1, delta)); // cap the delta to [-1,1] for cross browser consistency

    pos += -delta * speed;
    pos = Math.max(0, Math.min(pos, target.scrollHeight - target.clientHeight)); // limit scrolling

    if (!moving) {
        update();
    }
}

function update() {
    moving = true;
    var delta = (pos - window.pageYOffset) / smooth;
    console.log(window.pageYOffset);

    if (window.navigator.userAgent.indexOf("Edge") > -1) {
        window.pageYOffset += delta;
    }
    else {
        target.scrollTop += delta;
    }

    console.log(Math.abs(delta));

    if (Math.abs(delta) > 0.5) {
        console.log("entered if");
        requestFrame(update);
    }
    else {
        moving = false;
    }
}

var requestFrame = (function() {
    console.log("request frame is triggered");
    // requestAnimationFrame cross browser
    return (
        window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(func) {
            window.setTimeout(func, 1000 / 50);
        }
    );
})();}

为什么它不起作用?

【问题讨论】:

  • 如果您只使用window.requestAnimationFrame(function() {console.log('success');}); docs.microsoft.com/en-us/microsoft-edge/dev-guide/performance/… 会发生什么情况您可能以与 IE/edge 解释 javascript 的方式不兼容的方式调用它。
  • 我的控制台输出成功就好了,但是网页仍然明显锁定/不滚动。
  • 好的。所以 requestAnimationFrame 有效。如果用console.log函数调用自己的requestFrame函数,是不是也输出到console?
  • 是的,我在上面的原始代码中有console.log,它一直告诉我它被触发了,以及滚动时的位置变化。
  • 您可以尝试使用 window.scrollY 代替 scrollTop 吗?见stackoverflow.com/questions/20514596/…

标签: javascript microsoft-edge requestanimationframe


【解决方案1】:

这可能是因为事件循环.....因为在 Edge 中,questAnimationFrame 发生在渲染之后。

有关更多信息,请参阅 Jake Archibald 的精彩演讲!

https://www.youtube.com/watch?v=cCOL7MC4Pl0

【讨论】:

    猜你喜欢
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多