Angular 4 滚动元素偏移顶部值

Angular 4 Scroll Element Offset Top Value

In jQuery element.offset().top 给出固定元素当前从文档顶部的位置。当我向下滚动时,它会在向上滚动时变大,偏移量最高值会减小。

现在我需要 Angular 4 中的相同行为,但我缺少了一些东西,我的偏移顶部值仍然相同。

请看附件Plunker:https://embed.plnkr.co/3sDzpRcJMEN6lndw4MUB

 @Component({
  selector: '[my-app]',
  template: `
    <div>
      <h2>There is document top</h2>
      <div class="fixed-box" #fixedBox>
        <p>I'm fixed box</p>
        <p>I wanna know my offset from the document top (not viewport) in every scroll step</p>
        <p>My current position from the document top is: {{ fixedBoxOffsetTop }}px</p>
        <p>My current position from the document top is: {{ fixedBoxOffsetTopOtherMethod }}px</p>
      </div>
    </div>
  `,
})
export class App implements OnInit {
  fixedBoxOffsetTop: number  = 0;
  fixedBoxOffsetTopOtherMethod: number = 0;

  @ViewChild('fixedBox') fixedBox: ElementRef;

  constructor() {}

  ngOnInit() {}

  @HostListener("window:scroll", [])
  onWindowScroll() {
    this.fixedBoxOffsetTop = this.fixedBox.nativeElement.offsetTop; // This value looks like init value and doesn't change during scroll
    this.fixedBoxOffsetTopOtherMethod = this.fixedBox.nativeElement.getBoundingClientRect().top; // The same result as offsetTop
  }
}

有人可以帮忙吗?

您错过了 windowdocument 偏移:

const rect = this.fixedBox.nativeElement.getBoundingClientRect();
this.fixedBoxOffsetTop = rect.top + window.pageYOffset - document.documentElement.clientTop;

Forked Plunker

有我的方法:

getCurrentOffsetTop(element: ElementRef) {
  const rect = element.nativeElement.getBoundingClientRect();
  return rect.top + window.pageYOffset - document.documentElement.clientTop;
}