Angular 4滚动元素偏移顶值

Pav*_*rin 3 scroll offset angular

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

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

请参阅附件的柱塞: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
  }
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

yur*_*zui 5

您错过了windowdocument抵消了:

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

分叉柱塞