如果我在单独的HTML,CSS和Javascript文件中编写this codes并使用浏览器将其打开,则当在视口(viewport)高度中间观察到目标时,将显示粘性共享栏,而当在视口(viewport)高度底部观察到目标时,将在codepen中显示。是什么原因?

{
    class StickyShareBar {
        constructor(element) {
            this.element = element;
            this.contentTarget = document.getElementsByClassName('js-sticky-sharebar-target');
            this.showClass = 'sticky-sharebar--on-target';
            this.threshold = '50%';
            this.initShareBar();
        }

        initShareBar() {
            if(this.contentTarget.length < 1) {
              this.element.addClass( this.showClass);
              return;
            }
            if(intersectionObserverSupported) {
              this.initObserver();
            } else {
              this.element.addClass(this.showClass);
            }
        }

        initObserver() {
            const self = this;
            var observer = new IntersectionObserver(
              function(entries, observer) {
                self.element.classList.toggle( self.showClass, entries[0].isIntersecting);
              },
              {
               rootMargin: "0px 0px -"+this.threshold+" 0px"}
            );
            observer.observe(this.contentTarget[0]);
        }
    }

    const stickyShareBar = document.getElementsByClassName('js-sticky-sharebar'),
      intersectionObserverSupported = ('IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype);

    new StickyShareBar(stickyShareBar[0]);
}

最佳答案

rootMargin可能是一个问题,而您正在使用iframe
https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin

https://github.com/w3c/IntersectionObserver/issues/372

09-29 19:36