【问题标题】:Intersection Observer and removing the observed elementIntersection Observer 并移除观察到的元素
【发布时间】:2021-10-17 04:45:56
【问题描述】:

我在选取框中使用交叉点观察器,我正在观察第一个孩子何时离开视口,移除第一个孩子,将新的(相同的)第一个孩子向右移动其元素的宽度(使用 marginLeft) ,然后将另一个相同的子元素附加到父 div 的子元素的末尾。

这工作一次,但交叉点观察者不会第二次触发,即使新的第一个孩子与删除的孩子相同。

我想知道突变观察器在这里是否更有用,但不知道如何去做!

let firstChild = document.querySelector('.marquee').firstElementChild;
let target = firstChild;

let options = {
    root: null,
    threshold: 0,
  };
 
function onChange(changes) {
     changes.forEach(change => {
        if (change.intersectionRatio === 0) {
            firstChild.remove();
            console.log('Header is outside viewport');

            for ( i = 0; i < 100000; i++ ) {    
                if ( rectParent.childElementCount < 3 ) {
                    let child = document.createElement('p');
                    child.className = "global-chat";
                    child.innerHTML = "Something written here";
        
                    let docFrag2 = document.createDocumentFragment().appendChild(child.cloneNode(true));
                    rectParent.appendChild(docFrag2);
                    document.querySelector('.marquee').firstElementChild.style.marginLeft = `${boxWidth}` * `${i+1}` + "px";
                }
            }        
        }     
    });
}
 
let observer = new IntersectionObserver(onChange, options);

observer.observe(target);```



【问题讨论】:

    标签: javascript intersection-observer


    【解决方案1】:

    问题

    您定义IntersectionObserver 类并在observer 中实例化它。此时,firstChild 变量获得了正确的元素,但在下一次更改中,您的 firstChild 没有得到更新!

    解决办法

    您可以在onChange 函数中更新您的firstChild 元素,以确保在更改之前获取正确的元素。

    例如:

    function onChange(changes) {
         changes.forEach(change => {
            if (change.intersectionRatio === 0) {
                const firstChild = document.querySelector('.marquee').firstElementChild;
                firstChild.remove();
    
               // rest of the codes ...    
            }     
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多