简单的角度方式来检测元素是否在滚动的视口中



我正试图为我的Angular应用程序找到一个简单的解决方案,检查元素在滚动时是否可见,然后启动一些动画。所以,通常我只使用jQuerys Waypoint插件。但这并不是真正的角度方式。从不同的角度尝试后,我在这里遇到了这个npm包:ngui/common

ngui inview指令正是我想要的,但文档非常糟糕。它只是展示了我如何懒惰地加载图像。。。那不是我想要的。

这里有人有使用这个软件包的经验吗?我真的需要帮助

使用交集观测器:

// the element that you are observing (just add #yourElement in the template) for this  query to work
@ViewChild('yourElement') yourElement: ElementRef;
ngAfterViewInit() {
const threshold = 0.2; // how much % of the element is in view
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// run your animation code here
observer.disconnect(); // disconnect if you want to stop observing else it will rerun every time its back in view. Just make sure you disconnect in ngOnDestroy instead
}
});
},
{ threshold }
);
observer.observe(this.yourElement.nativeElement);
}

不需要任何额外的包/依赖项,这一功能现在是大多数现代浏览器的原生功能。

请参阅https://caniuse.com/intersectionobserver

更多详细信息:https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

最新更新