gpt4 book ai didi

javascript - DOM 元素可见性和 requestAnimationFrame

转载 作者:行者123 更新时间:2023-11-28 02:37:41 26 4
gpt4 key购买 nike

我正在阅读一篇关于 HTML5Rocks 的文章给出了一个关于滚动网页并检查 DOM 元素 offsetTop 数组以查看它们是否应该可见的示例。

文章说,执行此操作的最佳实践方法是每次触发滚动事件时使用 Windows 当前偏移顶部更新变量。当第一个滚动事件被触发时,它会触发检查 DOM 元素的 offsetTop 的 requestAnimationFrame 过程。这将可见性逻辑与滚动事件解耦。

虽然我了解将这两个进程解耦的好处(因为滚动事件每秒可以调用数百次),但无论如何,我看不到在第一个滚动事件之后每 16 毫秒运行一次可见性逻辑的好处用户是否继续移动..

有人可以解释一下我在这里缺少流程的哪一部分吗?

最佳答案

我认为文章中对此进行了很好的解释。

What else can we do? Well for one thing we are constantly runningrequestAnimationFrame and that’s not necessary if we haven’t justscrolled since nothing will have changed. To fix that we have theonScroll initiate the requestAnimationFrame

Now whenever we scroll we will try and call requestAnimationFrame, butif one is already requested we don’t initiate another. This is animportant optimization, since the browser will stack all the repeatedrAF requests and we would be back to a situation with more calls toupdate than we need.

Thanks to this setup we no longer need to call requestAnimationFrameat the top of update because we know it will only be requested whenone or more scroll events has taken place. We also no longer need thekick off call at the bottom, either, so let’s update accordingly:

var latestKnownScrollY = 0,
ticking = false;

function onScroll() {
latestKnownScrollY = window.scrollY;
if (!ticking) {
requestAnimationFrame(update);
}
ticking = true;
}
function update() {
ticking = false; // reset the tick so we can capture the next onScroll

var currentScrollY = latestKnownScrollY;

// Do visibilty logic and animation here
}

因此,“无论用户是否继续移动”并不是真的。 update 仅在滚动期间(或稍后)以浏览器选择的帧速率而不是每秒数百个事件的速率调用。

关于javascript - DOM 元素可见性和 requestAnimationFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com