加载页面后,离子3视图子滚动事件侦听器将不会执行

时间:2018-07-18 23:21:02

标签: javascript ionic-framework ionic3 scrolltop viewchild

我使用了{strong> Slides (幻灯片)将ViewChild放在<ion-scroll>内的<ion-slides>元素中。现在,当页面进入或加载时,即使页面已加载,我也想知道该滚动的scrollTop位置。

这是我的 ts文件

中下面的代码示例
@ViewChild('mySlider') slider: Slides;

请参阅此元素<ion-scroll #scrollWeb scrollY="true">

现在加载页面并获得this.scrollWeb,在页面第一次加载后页面无法识别它。

ionViewWillEnter() {
    this.getPosts()
    // console.log('Slider:', this.slider);
    console.log(this.scrollWeb)
    if (this.scrollWeb) {
      this.scrollWeb.addScrollEventListener((ev) => {
        console.log(ev.target.scrollTop)
        if (ev.target.scrollTop < 2) {
          this.pulling = true
          console.log('Less than two')
        } else {
          this.pulling = false
        }
      })
    }

页面进入时,scrollWebundefined未知。但是当我打开另一个页面然后再返回时,scrollWeb现在是已知的。但是奇怪的是,它仅在我返回该页面时才执行事件。但是为什么呢?

这是 html文件

的完整副本
<ion-slides #mySlider (ionSlideDidChange)="onSlideChanged($event)" *ngIf="!spinner">

    <!-- Discover -->
    <ion-slide>
      <ion-scroll #scrollWeb scrollY="true">
        <div class="pins" [ngStyle]="{'margin-top': selectedSegment=='second' ? '42px' : '0'}">

          <ion-card class="pin" *ngFor="let post of posts" no-padding [ngStyle]="{'display': post?.hidden ? 'none' : 'inline-block'}">
           <!-- Some content here -->
          </ion-card>
        </div>
      </ion-scroll>
    </ion-slide>
   </ion-slides>

我第一次打开页面时没有日志。

但是当我转到另一个页面并决定返回时,scrollWeb已经在下面显示它的日志:

Scroll {_scrollX: false, _scrollY: true, _zoom: false, _maxZoom: 1, maxScale: 3, …}
maxScale
:
3
maxZoom
:
(...)
scrollX
:
(...)
scrollY
:
(...)
zoom
:
(...)
zoomDuration
:
250
_maxZoom
:
1
_scrollContent
:
ElementRef
nativeElement
:
div.scroll-content
__proto__
:
Object
_scrollX
:
false
_scrollY
:
true
_zoom
:
false

上面的日志应该在我正确加载页面时执行吗?因为我将其放在IonViewWillEnter方法内。甚至IonViewDidLoad也不起作用。

仅当我转到另一页并返回并使其运行时,它才起作用。

我试图将其放在构造函数上,但即使我导航到其他页面并在代码位于构造函数中返回时也无法正常工作。

有人可以给我一些启发吗?

感谢有人可以帮助您。 预先感谢。

1 个答案:

答案 0 :(得分:0)

这只是解决相同问题的临时解决方案。

我只是放了setTimeout方法并在一秒钟后在内部执行操作。

此处的代码:

 setTimeout(() => {
      console.log(this.scrollWeb)
      if (this.scrollWeb) {
        this.scrollWeb.addScrollEventListener((ev) => {
          console.log(ev.target.scrollTop)
          if (ev.target.scrollTop < 2) {
            this.pulling = true
            console.log('Less than two')
          } else {
            this.pulling = false
          }
        })
      }
    }, 1000)

这只是一个临时解决方案,但在平板电脑等其他设备上运行良好。在AndroidiOS 平台经过测试和证明的情况下,它也能很好地工作。

PS::我不知道IonViewDidLoad有什么问题,但是我认为这是可以使用的正确方法。如果我错了请纠正我

相关问题