【问题标题】:Ionic 3 view child scroll event listener won't execute when the page is loaded加载页面时不会执行 Ionic 3 视图子滚动事件侦听器
【发布时间】:2018-07-18 23:21:01
【问题描述】:

我使用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 也不起作用。

它只有在我转到另一个页面并返回并运行它时才有效。

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

有人可以帮我解释一下吗?

如果有人可以提供帮助,我们将不胜感激。 提前致谢。

【问题讨论】:

    标签: javascript ionic-framework ionic3 scrolltop viewchild


    【解决方案1】:

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

    我只是放了一个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 有什么问题,但我认为这是应该习惯的正确方法。如果我错了,请纠正我

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 2011-11-29
      • 1970-01-01
      • 2019-11-27
      相关资源
      最近更新 更多