import { Component, OnInit } from '@angular/core';
declare var IntersectionObserver: { new (callback: IntersectionObserverCallback, options?: IntersectionObserverInit): IntersectionObserver; };
ngOnInit() { let options = { root: null, // viewport rootMargin: '0px', threshold: [0, 0.25, 0.5, 0.75, 1] // different thresholds }; const observer = new IntersectionObserver(this.handleIntersect.bind(this), options); observer.observe(document.querySelector('.your-class')); // observe any element with 'your-class' class }
handleIntersect(entries, observer) { entries.forEach((entry: any) => { if (entry.intersectionRatio > 0) { // element is in view } else { // element is out of view } }); }
这里给出了一个简单的示例,要使用它,只需将'your-class'替换为要监视的元素的类名即可。注意,IntersectionObserver仍然属于实验性API,某些浏览器可能不支持或需要前缀。