【问题标题】:Intersection Observer not working with siblings交叉口观察员不与兄弟姐妹一起工作
【发布时间】:2019-11-14 11:46:52
【问题描述】:

我有一个有 4 个孩子的 flexbox 容器,每个孩子都有with:50%

我想为每个孩子创建一个 IO(Intersection Observer),但由于某种原因,它只适用于 1º 和 3º 元素...但是如果我为 2º 和 4º 元素创建一个新的 IO,它可以工作。

我做错了什么?

这是演示:https://codepen.io/sandrina-p/pen/mddzpzW

【问题讨论】:

    标签: javascript intersection-observer


    【解决方案1】:

    你的代码是这样的:

    const watchContainer = ([entry]) => {
        console.log('IO card:', entry.target);
        entry.target.style.opacity = entry.isIntersecting ? '1' : '0';
    };
    

    应该是这样的:

    const watchContainer = (entries) => {
        entries.forEach(entry => {
            console.log('IO card:', entry.target);
            entry.target.style.opacity = entry.isIntersecting ? '1' : '0';
        })
    };
    

    按照你的方式,如果多个元素同时触发观察者,它只会在第一个元素上运行该函数。按照我的方式,它会在每个匹配的条目上运行它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      相关资源
      最近更新 更多