angular 2 基于 id 滚动到顶部的距离

angular 2 distance from top on scroll based on id

我正在为我的一个项目使用 angular 2。我有 3 个 table 高度未知,即它可以 growing.Now 滚动,我想知道是否元素的顶部已经通过顶部导航栏,即如果第一个 table 被滚动而第二个是可见的,我需要初始化一个变量以便我可以做进一步的事情 operations.I 尝试使用 viewchild as

@ViewChild('leaveApproval') element:ElementRef;
console.log(this.element.nativeElement.topOffset);

并在 html

  <div class="twelve wide right floated column" #leaveApproval>

但 console.log 总是 returns "undefined"。我该如何解决这个问题或如何解决这个问题

你用错了属性。正确的是this.element.nativeElement.offsetTop


更新:

以下是获取活动 table 并相应地执行进一步操作的方法:

  1. 假设您的顶部导航栏有 id navBar,获取导航栏元素:

    @ViewChild('navBar') navBar: ElementRef;

  2. 获取 tables,假设使用 ID tableOnetableTwo:

    @ViewChild('tableOne') tableOne: ElementRef;
    @ViewChild('tableTwo') tableTwo: ElementRef;
    
  3. 这是一个将 return 可见 table 参考的函数:

    getVisibleTable(): ElementRef
    {
        let visibleTable: ElementRef = null;
        const navBarHeight = this.navBar.nativeElement.height;
        const tableOneTopOffset = this.tableOne.nativeElement.offsetTop;
        const tableTwoTopOffset = this.tableOne.nativeElement.offsetTop;
    
        if (tableOneTopOffset >= navBarHeight) 
        {
            visibleTable = this.tableOne;
        }
        else if (tableOneTopOffset < navBarHeight)
        {
            if (tableTwoTopOffset >= navBarHeight)
            {
                visibleTable = this.tableTwo;
            }
            else
            {
                visibleTable = null;
            }
        }
    
        return visibleTable;
     }