【问题标题】:Angular 4 Scroll Element Offset Top ValueAngular 4 滚动元素偏移顶部值
【发布时间】:2018-01-08 20:34:19
【问题描述】:

在 jQuery 中 element.offset().top 从文档顶部给出固定元素的当前位置。当我向下滚动时,它会在向上滚动时增大,偏移量顶部值会减小。

现在我需要 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
  }
}

有人可以帮忙吗?

【问题讨论】:

  • 您可能希望在问题正文中包含代码。该链接肯定会在某一天失效,从而使这个问题失去意义。

标签: angular scroll offset


【解决方案1】:

您错过了windowdocument 偏移量:

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

Forked Plunker

【讨论】:

  • 这仍然不适合调整窗口大小... ;-)
  • @JGFMK 他不听resize 事件。看到这个plnkr.co/edit/PLZfad6kQZuHR3qAqxWk?p=preview
  • plnkr.co/edit/Z0cSqqJJXWw6dpPeHMbs?p=preview - 最初执行并输出它。我认为也有一种方法可以将多个事件绑定到处理程序 - github.com/TheLarkInn/angular2-multievent-bindings-plugin/blob/…
  • 在那里学到了一些东西 - 没有意识到您可以在一个方法上使用多个 HostListener...
  • 谢谢,正是我想要的。遗憾的是,您需要那两行而不是一个单词。如果有人想要一个词,有自定义函数:` /** * 返回元素相对于文档的坐标 * @param element * @returns {number} */ getCurrentOffsetTop(element: ElementRef) { const rect = element.nativeElement.getBoundingClientRect( );返回 rect.top + window.pageYOffset - document.documentElement.clientTop; }`
【解决方案2】:

这是我的方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多