首页 > 解决方案 > 如何在Angular中使用名为“dropdown”的类获取topOffset

问题描述

我在 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;
  }

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

标签: angulardropdownoffsetpopover

解决方案


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中看到


推荐阅读