Angular 4 Scroll Element Offset Top Value
在jQuery中,element.offset()。top给出文档顶部的固定元素当前位置。当我向下滚动时,滚动偏移量最大值时会增长。Angular 4 Scroll Element Offset Top Value
现在我需要在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
}
}
有人能帮忙吗?
你错过了window
和document
偏移:
const rect = this.fixedBox.nativeElement.getBoundingClientRect();
this.fixedBoxOffsetTop = rect.top + window.pageYOffset - document.documentElement.clientTop;
这仍然不适合窗口大小调整... ;-) – JGFMK
@JGFMK他不听'resize'事件。看到这个https://plnkr.co/edit/PLZfad6kQZuHR3qAqxWk?p=preview – yurzui
https://plnkr.co/edit/Z0cSqqJJXWw6dpPeHMbs?p=preview - 这样做并输出它最初。我认为有一种方法可以将多个事件绑定到一个处理程序上 - https://github.com/TheLarkInn/angular2-multievent-bindings-plugin/blob/master/README.md – JGFMK
还有就是我为这个方法:
getCurrentOffsetTop(element: ElementRef) {
const rect = element.nativeElement.getBoundingClientRect();
return rect.top + window.pageYOffset - document.documentElement.clientTop;
}
你可能想要在体内的代码你题。这种联系肯定会有一天结束,这个问题就没有意义了。 – jdv