【问题标题】:Getting position of native element relative to viewport via Angular 2通过Angular 2获取本机元素相对于视口的位置
【发布时间】:2018-12-25 17:57:35
【问题描述】:

我正在使用 @ViewChild 访问我的模板中的原生 DOM 元素。我想弄清楚这个元素在视口中的位置。

this.myElement.nativeElement.???

我相信我需要在这里获取一些数据点来解决这个问题。

我可以通过以下方式获取视口的高度:

window.innerHeight

但是我很困惑如何使用 Angular 找到 myElement 相对于所述视口的位置。

【问题讨论】:

标签: javascript angular dom


【解决方案1】:

使用getBoundingClientRect

constructor(private ele: ElementRef<HTMLElement>)
{

}

// scrolls an element into view if it's too close to the top of the screen
scrollIntoView() 
{
      var bounds = this.ele.nativeElement.getBoundingClientRect();

      if (bounds.top < 50)
      {
          window.scrollBy(0, -50 + bounds.top );
      }
}

【讨论】:

  • 我建议为这样的东西创建一个 ScrollService 来注入元素 ref - 然后你的组件注入滚动服务并在其上调用 scrollIntoView()。 #干
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 2010-11-23
  • 2017-07-23
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
相关资源
最近更新 更多