当元素在视图中时进行角度检查 [英] Angular check when an element is in view

查看:44
本文介绍了当元素在视图中时进行角度检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角度视图中,如何检测某个元素是否在视野中?

In angular, how do I detect if a certain element is in view?

例如,我有以下内容:

<div class="test">Test</div>

有没有一种方法可以检测该div何时显示?

Is there a way to detect when this div is in view?

谢谢.

推荐答案

基于此 answer (适用于Angular):

Based off this answer, adapted to Angular:

模板:

<div #testDiv class="test">Test</div>

组件:

@ViewChild('testDiv') private testDiv: ElementRef<HTMLDivElement>;

isScrolledIntoView(){
  if (this.testDiv){
    const rect = this.testDiv.nativeElement.getBoundingClientRect();
    const topShown = rect.top >= 0;
    const bottomShown = rect.bottom <= window.innerHeight;
    this.isTestDivScrolledIntoView = topShown && bottomShown;
  }
}

具有滚动事件绑定的示例

另一个不错的功能是确定将多少< div> 视为在视图内".此处是此类实现的参考.

Another nice feature is to determine how much of that <div> is to be considered as "within view". Here's a reference to such implementation.

这篇关于当元素在视图中时进行角度检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆