首页 > 解决方案 > 确定组件是否在屏幕中可见

问题描述

我使用 Nativescript + Angular,这是我的代码:

<ScrollView class="body" id="scroll" #scroll (scroll)="scrollEvent($event);">
    <StackLayout #stackScroll>

        <ng-template ngFor let-card [ngForOf]="allList">
            <StackLayout [card]="card">

                <my-custom-component [aCard]="card"></my-custom-component>

            </StackLayout>
        </ng-template>

    </StackLayout>
</ScrollView>

我使用了这段代码,效果很好:

https://discourse.nativescript.org/t/how-to-detect-if-component-is-in-screen-view-is-visible/1148/4

我可以更改“ng-template”中“StackLayout”的背景颜色。

但我无法访问我的自定义组件变量来修改他的行为。

例如,如果显示“my-custom-component”,我想更改“aCard”属性中传递的“card”对象中的属性“isShown”。

谢谢大家 :)

EDIT1:“isShown”是我用于此测试的自定义变量。我的想法是在 afterScroll 函数中计算可见的卡片是什么,并将参数传递给 aCard 以改变他的行为。

标签: nativescriptvisibilityshow-hideangular2-nativescriptnativescript-angular

解决方案


您可以在滚动事件时找到 ScrollView 中每个子组件的位置,将其与垂直偏移量进行比较可以让您知道该组件是否真的在屏幕上可见。

这是一个游乐场示例。当您向下/向上滚动时,可见组件的背景颜色将变为绿色,否则变为红色。

onScroll(event: EventData) {
    const scrollView = <ScrollView>event.object,
        verticalOffset = scrollView.verticalOffset,
        height = scrollView.getActualSize().height,
        visibleRange = verticalOffset + height,
        container = <StackLayout>this.container.nativeElement;

    let index = 0;
    container.eachLayoutChild((childView) => {
        const locationY = childView.getLocationRelativeTo(container).y;
        this.cards[index].isShown = locationY >= verticalOffset && locationY <= visibleRange
        index += 1;
    });
}

推荐阅读