【问题标题】:Why IntersectionObserver is not applying the classes?为什么 IntersectionObserver 不应用这些类?
【发布时间】:2021-06-16 22:12:14
【问题描述】:

我正在关注有关 IntersectionObserver 的教程,但我似乎无法让它工作......我正在尝试对视口中可见的元素应用动画。我将在此处粘贴 JS 代码,此处包含 html 和 css 的完整示例:https://codepen.io/cucurutcho/pen/KKWRrov

    const images = document.querySelectorAll('.anim');

    console.log("I'm working!");

    observer = new IntersectionObserver((entries) => {

        entries.forEach(entry => {
          console.log("I'm working 2!");
            if(entry.intersectionRatio > 0) {
                entry.target.style.animation = `fadeInUp animated animatedFadeInUp`;
            }
            else {
                entry.target.style.animation = 'none';
            }
        })

    })

    images.forEach(image => {
      console.log("I'm working 3!")
        observer.observe(image)
    })

    

非常感谢任何帮助!非常感谢大家

【问题讨论】:

    标签: javascript html css intersection-observer


    【解决方案1】:

    您不是针对类,而是在覆盖 CSS animation 属性的文本内容,如 here 所述。

    你需要 classList 代替:

    if (entry.intersectionRatio > 0) {
      entry.target.classList.add("fadeInUp", "animated", "animatedFadeInUp")
    } else {
      entry.target.classList.remove("fadeInUp", "animated", "animatedFadeInUp")
    }
    

    【讨论】:

    • 感谢您的建议@lawrence-witt,我尝试使用它,但也没有应用这些课程?可能代码的其他地方有问题
    • 将它插入您的代码笔以代替之前的条件,它就可以工作了。此处无需添加更多内容。
    • 它确实有效@lawrence-witt,在我的本地机器上它不是,当我将JS负载移动到身体的末端时我得到了解决,而不是在头部!再次感谢您的帮助,先生
    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多