如何将动态生成的元素绑定到 Intersection Observer?

Mar*_*cel 6 javascript intersection-observer

这是我正在使用的代码:

var ob = new IntersectionObserver(entries => {
    for(var entry of entries){
        console.log('works');
    }
});

document.querySelectorAll('dynamicElement').forEach(elem => ob.observe(elem));
Run Code Online (Sandbox Code Playgroud)

这适用于页面上的元素,但不适用于稍后动态创建的元素。如何绑定稍后插入页面的元素?

我知道使用 jquery 可以绑定它$(document).on('event', 'element', 'func');,但是我如何使用观察者来绑定它?

ele*_*ixG 2

老问题,但基本上我最近遇到了同样的问题,并且在网上没有找到任何答案,因此在调查之后,明显的解决方案是将 MutationObserver() API 与 IntersectionObserver() 一起使用。

基本上,您选择动态生成的子元素的非动态父元素,并将一个mutationObserver附加到其childList。

随后,在检测到突变时(在突变观察器回调上),您选择动态生成的元素并将交集观察器附加到它。

此外,如果您使用 querySelectorAll,您还可以使用 forEach 将交叉观察器附加到您在问题中建议的所有动态元素。

就像是:

// Mutation Observer
   
const mSection = chatSection.querySelector(".non-dynamic-parent"),
    mObsOptions = {
      childList: true,
    },
    mObserver = new MutationObserver(mObs_CB);

  function mObs_CB(mutations) {
    for (let mutation of mutations) {
      if (mutation.type === "childList") {
        console.log("Mutation Detected");        

        //Start the Intersection Observer Here
        const intObsAllElem = document.querySelectorAll(".dynamicElement");        
        intObsAllElem.forEach(function (elem) {
          intObserver.observe(elem);
        });
      }
    }
  }

  mObserver.observe(mSection, mObsOptions);

 
//Intersection Observer
  
   const intObsOptions = {
         root: null,
         threshold: 1,
         rootMargin: "0px",
    },
    intObserver = new IntersectionObserver(intObs_CB, intObsOptions);

  function intObs_CB(entries, observer) {
      entries.forEach((entry) => {
         if (entry.isIntersecting) {
            console.log("intersecting");
         } else {
            console.log("not intersecting");
         }

      });

  }
Run Code Online (Sandbox Code Playgroud)