简单 Angular 检测元素是否在滚动视口中的方法

Easy Angular way to detect if element is in viewport on scroll

我正在尝试为我的 Angular 应用程序找到一个简单的解决方案,以检查元素在滚动时是否可见,如果它是则触发一些动画。 所以,通常我只使用 jQuerys Waypoint 插件。但这并不是真正的 Angular 方式。从不同角度尝试后,我在这里遇到了这个 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);
    }

不需要任何额外的 packages/dependencies 此功能现在是大多数现代浏览器的原生功能。

https://caniuse.com/intersectionobserver

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