【问题标题】:angular 2 distance from top on scroll based on id基于 id 滚动到顶部的角度 2 距离
【发布时间】:2018-01-07 04:31:27
【问题描述】:

我在我的一个项目中使用 angular 2。我有 3 个高度未知的表格,即它可以增长。现在滚动时,我想知道元素的顶部是否已通过顶部导航栏,即如果第一个表被滚动,第二个是可见的,我需要初始化一个变量,以便我可以做进一步的操作。我尝试使用 viewchild as

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

在html中

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

但是console.log总是返回“未定义”。我该如何解决这个问题或如何解决这个问题

【问题讨论】:

  • 请提供一个 Plunker 示例。从提供的信息来看,问题所在尚不清楚。

标签: html angular angular2-template angular2-directives


【解决方案1】:

您使用了错误的属性。正确的是this.element.nativeElement.offsetTop


更新:

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

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

    @ViewChild('navBar') navBar: ElementRef;

  2. 获取表格,假设 ID 为 tableOnetableTwo

    @ViewChild('tableOne') tableOne: ElementRef;
    @ViewChild('tableTwo') tableTwo: ElementRef;
    
  3. 这是一个返回可见表引用的函数:

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

【讨论】:

  • 该死的..我太傻了..非常感谢..回答了我的一半问题。请回答如何知道元素是否已经通过元素的顶部,以便答案可以被接受
  • 如果您思考并应用正确的逻辑,那应该很容易:) 获取顶部元素引用并获取当前元素引用,否则其余的应该很简单......
  • 是的,没错。我明白了,但是对于以后阅读这篇文章的其他人来说:)
  • @vikk 我已经用示例代码更新了我的答案以获取可见表。
猜你喜欢
  • 1970-01-01
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
相关资源
最近更新 更多