繁体   English   中英

当元素相交时,如何在每个像素处获得 Intersection Observer 回调触发器?

[英]How can I get the Intersection Observer callback trigger at every pixel when the element is intersecting?

我正在使用 Intersection Observer API 来帮助我实现视差效果。 到目前为止,除了一种情况外,一切都运行良好:

当图像已经可见并且在页面中间时,只要图像不与视口边缘相交,就不会触发回调。 所以我无法使用从回调接收到的 boundingClientRect 更新视差转换的位置。

    buildThresholdList(element) {
        let thresholds = [];
        let elementHeight = element.getBoundingClientRect().height;
        for (var i=1.0; i<=elementHeight; i++) {
            var ratio = i/elementHeight;
            thresholds.push(ratio);
        }

        return thresholds;
    }

    createIntersectionObserver(element) {
        const options = {
            root: null,
            threshold: this.buildThresholdList(element),
        }
        this.observer = new IntersectionObserver(this.intersectionObserverCallback, options);
    }

    intersectionObserverCallback(entries) {
        entries.forEach(entry => {
            let target = entry.target;

            if (entry.isIntersecting) {
                //calculate the translated value
                this.getTranslateValue(entry);
            }
         }
    }

即使图像完全可见并且不与任何东西相交,Intersection Observer API 是否有办法进行回调?

Chrome 的一个快速解决方法(因为这似乎是 Chrome 特定的问题)是在动画发生时触发布局计算。 添加这样的东西似乎可行,但您可能希望添加一些 transitionstart/transitionend 事件以确保它仅在转换处于活动状态时运行。

  const refresh = () => {
    image.clientWidth // triggers layout, which triggers intersection to be recalculated
    requestAnimationFrame(refresh)
  }
  requestAnimationFrame(refresh)

演示: https : //jsfiddle.net/01qa26L5/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM