如何获得有关Angular2中元素的当前位置信息 [英] How can you get current positional information about an element in Angular2

查看:163
本文介绍了如何获得有关Angular2中元素的当前位置信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有导航栏的ElementRef,我试图找出它离窗口顶部的距离有多近,以便使其具有粘性

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;

我正在滚动事件中打印出它的nativeElement的位置,但是值似乎是静态的

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?

推荐答案

offsetTop相对于文档中的位置,而不是相对于视口.

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.

例如var viewportOffset = el.getBoundingClientRect().top;

这篇关于如何获得有关Angular2中元素的当前位置信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆