在 angular 中,如何检测某个元素是否在 View 中?
例如,我有以下内容:
<div class="test">Test</div>
有没有办法检测这个 div 何时出现?
谢谢。
最佳答案
基于此 answer ,适应 Angular:
模板:
<div #testDiv class="test">Test</div>
成分: @ViewChild('testDiv', {static: false}) private testDiv: ElementRef<HTMLDivElement>;
isTestDivScrolledIntoView: boolean;
@HostListener('window:scroll', ['$event'])
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;
}
}
Example with scroll event binding另一个不错的功能是确定其中的多少
<div>
被视为“在视野之内”。 Here's a reference到这样的实现。
关于元素在 View 中时的 Angular 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49215634/