2017-08-01 105 views
1

在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 
    } 
} 

有人能幫忙嗎?

+0

你可能想要在體內的代碼你題。這種聯繫肯定會有一天結束,這個問題就沒有意義了。 – jdv

回答

0

你錯過了windowdocument偏移:

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

Forked Plunker

+0

這仍然不適合窗口大小調整... ;-) – JGFMK

+1

@JGFMK他不聽'resize'事件。看到這個https://plnkr.co/edit/PLZfad6kQZuHR3qAqxWk?p=preview – yurzui

+0

https://plnkr.co/edit/Z0cSqqJJXWw6dpPeHMbs?p=preview - 這樣做並輸出它最初。我認爲有一種方法可以將多個事件綁定到一個處理程序上 - https://github.com/TheLarkInn/angular2-multievent-bindings-plugin/blob/master/README.md – JGFMK

0

還有就是我爲這個方法:

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