How can you get current positional information abo

2020-08-26 11:29发布

问题:

I have the ElementRef of my navbar and I'm trying to find out how close it is to the top of my window so I can make it sticky

<div class="nav-bar" #navBar>

</div>

@ViewChild("navBar")
  navBarElement;

I'm printing out the positions of it's nativeElement in a scroll event but the values seem to be static

@HostListener('window:scroll', ['$event'])
onScroll(event) {
   console.log("offset top", this.navBarElement.nativeElement.offsetTop);
}

How can I track the current position of my element?

回答1:

offsetTop is relative to it's place in the document, not relative to the view port.

See How to get an element's top position relative to the browser's window? for how to get the scroll position.

eg. var viewportOffset = el.getBoundingClientRect().top;



标签: angular