【问题标题】:Is it possible to trigger Intersection Observer callback every scroll/pixel?是否可以在每个滚动/像素触发 Intersection Observer 回调?
【发布时间】:2020-09-06 19:59:29
【问题描述】:

我在动画中使用 Intersection Observer API 而不是滚动事件,但在尝试根据滚动位置和滚动值沿 offset-path 设置 SVG 动画时遇到了问题。

path.style.offsetDistance = element.intersectionRatio * 100 + "%";

由于 Intersection Observer 回调在每次通过 options 对象中定义的 threshold 值时都会触发,因此使用 element.intersectionRatiooffset-distance 设置动画会给我一个错误的动画,它只会每 25% 的滚动百分比触发一次。我可以将选项对象中的每 1% 作为阈值,如下所示:

let options = {
  root: null,
  rootMargin: "20px",
  threshold: [0.01, 0.02, 0.03, 0.04, .....]
};

但是有更好的解决方案还是我应该切换到旧的滚动事件并在公式中使用 scrollY 值来平滑地计算每个滚动/像素的偏移距离?

其余代码:

let options = {
  root: null,
  rootMargin: "20px",
  threshold: [0, 0.25, 0.5, 0.75, 1]
};

let callback = (entries, observer) => {
    entries.forEach(element => {
        if (element.isIntersecting) {
            element.target.querySelectorAll("path").forEach(path => {
                path.setAttribute("style", "offset-path: path('M" + generateRandomAnimationPathM() +" " + generateRandomAnimationPathM() + " L " + generateRandomAnimationPathLine() + " " + generateRandomAnimationPathLine() + "')", "offset-rotate: 0deg");
                path.style.offsetDistance = element.intersectionRatio * 100 + "%";
            });
        }
    });   
}

let generateRandomAnimationPathM = () => {
    return Math.floor(Math.random() * Math.floor(100));
}

let generateRandomAnimationPathLine = () => {
    return Math.floor(Math.random() * Math.floor(200));
}

let observer = new IntersectionObserver(callback, options);

document.querySelectorAll('section').forEach(section => {
    console.log(section)
    observer.observe(section);
});

【问题讨论】:

    标签: javascript svg intersection-observer


    【解决方案1】:

    值得注意的是,您提出的阈值技巧是一种技巧,不能保证 100% 的时间有效。
    这是因为 IntersectionObserver API 在内部使用 window.requestIdleCallback ,它将请求浏览器仅在有时间且用户未与其交互时才执行回调。这意味着即使在每 0.01 步设置阈值后,动画仍然可能导致故障,因为某些步骤可能会被跳过。
    正如您已经说过的,您可以轻松完成您想要实现的目标,方法是使用 window.scrollY 计算元素在 scrollEvents 上的交叉率。

    【讨论】:

    • 谢谢。我已经最终使用了阈值破解,但随着时间的推移可能会放弃观察者并切换到滚动事件。在整个互联网上,每个人都在说滚动事件已经过时了,你应该使用 Observer API,但没有人谈论这样的异常。
    • 当然,intersectionObserver 是一个较新的 API,它允许做很多以前只能使用 scrollEvent 的事情(延迟加载、定时动画、基于滚动位置的事件触发器等等......)但它不是它的替代品,它从来都不是!希望现在清楚一点??
    • 绝对。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多