0

我在 Angular 中需要与 jQuery/HTML 相同的结果。使用 jQuery,无论是否滚动,我都会得到相同的 topOffset 值。

// get the top offset of the dropdown (distance from top of the page)
var topOffset = $(".dropdown").offset().top;

供您参考,在 Angular 中,我将模板变量与@ViewChild一起使用,但 topOffset 值已更改,并且没有提供与 jQuery 相同的所需结果。

  @ViewChild('dp') dropdown: ElementRef
  functionName() {
     let topOffset = this.dropdown.nativeElement.getBoundingClientRect().top;
  }

请在评论中告诉我,我必须做什么才能达到所需的结果。

4

3 回答 3

0

jQuery 是开源的,如果您在 github(此链接)中查找,您会看到

offset: function( options ) {
    ...
    rect = elem.getBoundingClientRect();
    win = elem.ownerDocument.defaultView;
    return {
        top: rect.top + win.pageYOffset,
        left: rect.left + win.pageXOffset
    };
 }

如您所见,您需要添加 win.pageYOffset

所以你可以创建一个函数

  getOffset(element:HTMLElement){
    const rect = element.getBoundingClientRect();
        const win = element.ownerDocument.defaultView;
        return {
            top: rect.top + win.pageYOffset,
            left: rect.left + win.pageXOffset
        };
  }

并使用

this.offset= this.getOffset(this.dropdown.nativeElement)

你可以在这个 stackblitz中看到

于 2021-09-01T16:59:51.007 回答
0

您可以使用 offsetTop 而不是 getBoundingClientRect().top

 @ViewChild('dp') dropdown: ElementRef
  functionName() {
     let topOffset = this.dropdown.nativeElement.offsetTop;
  }

在这里查看一个简单的示例:

https://stackblitz.com/edit/angular-ivy-6jmua2?file=src%2Fapp%2Fapp.component.html

于 2021-09-01T17:19:21.153 回答
0

只需添加.top offsetTop 是相对于它在文档中的位置,而不是相对于视口

您可以使用此从文档顶部获取 offsetTop

 this.dropdown.nativeElement.getBoundingClientRect().top
于 2021-09-01T13:35:12.390 回答