当元素在屏幕(视口)上可见时触发功能 [英] Trigger function when element is visible on screen (viewport)

查看:61
本文介绍了当元素在屏幕(视口)上可见时触发功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery具有插件出现或航路点,以检测元素在视口中是否可见.我做了一些研究,我找不到并想知道Angular2是否具有类似的插件.如果还没有,那么做这种事情的最好方法是什么?

jQuery has the plugin appear or waypoint to detect if element is visible or not in viewport. I did some research, I can not find and wonder if Angular2 has a similar plugin. If not yet, what is the best way to do something like that?

推荐答案

这是我的方法:

sync-dom.utils.ts

static isInViewPort(rect: ClientRect, threshold = 0) {
    return rect &&
        rect.height &&
        rect.top + rect.height + threshold >= 0 &&
        rect.left + rect.width + threshold >= 0 &&
        rect.bottom - rect.height - threshold <= SyncDomUtils.windowHeight &&
        rect.right - rect.width - threshold <= SyncDomUtils.windowWidth;
}

dom.utils.ts

async isInViewPort(rect: ClientRect) {
    return SyncDomUtils.isInViewPort(rect);
}

在您的组件中,您将执行以下操作:

and in your component you do:

async isInViewPort() {
    // you have to import the Renderer and ElementRef from angular/core
    this.boundingRect = await this.domElementUtils
        .invokeElementMethod(this.renderer, this.el.nativeElement, 'getBoundingClientRect');

    return await this.domUtils.isInViewPort(this.boundingRect);
}

并将该函数用作this.isInViewPort(),它将返回一个布尔值

and use that function as this.isInViewPort() and it will return a boolean

这是我在 dom-element.utils.ts

async invokeElementMethod<T extends keyof HTMLElement>(renderer: Renderer, element: any, methodName: T, args?: any[]) {
    return await renderer.invokeElementMethod(element, methodName, args) as any;
}

这篇关于当元素在屏幕(视口)上可见时触发功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆