【发布时间】:2018-01-08 20:34:19
【问题描述】:
在 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
}
}
有人可以帮忙吗?
【问题讨论】:
-
您可能希望在问题正文中包含代码。该链接肯定会在某一天失效,从而使这个问题失去意义。