【问题标题】:Easy Angular way to detect if element is in viewport on scroll简单的角度方法来检测元素是否在滚动的视口中
【发布时间】:2022-01-13 19:15:33
【问题描述】:

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

ngui-inview 指令 正是我正在寻找的,但文档非常糟糕。它只是展示了我如何延迟加载图像......这不是我想要的。

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

【问题讨论】:

标签: angular angularjs scroll angular-directive


【解决方案1】:

使用交叉点观察器:

    // 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2011-09-14
    • 2023-04-08
    • 2012-11-28
    • 1970-01-01
    相关资源
    最近更新 更多