Angular 8 window 滚动事件未在移动浏览器上触发

Angular 8 window scroll events not firing on mobile browsers

我几乎尝试了所有在线可用的解决方案,但没有任何效果,以下是我尝试过的几个解决方案

我的实际情况是当屏幕向下滚动时另一个 div 元素从屏幕上消失时显示特定的 div 元素。

我可以在 desktops/laptops 上执行此操作,但不能在根本不触发滚动事件的手机上执行此操作。

我使用的台式机/笔记本电脑滚动事件侦听器是

@HostListener('window:scroll', ['$event']) getScrollHeight(event) {
  console.log('from desk' , window.pageYOffset, event);
}

而对于移动设备,因为我的滚动事件没有触发,所以我在下面使用了

@HostListener('window:touchStart', ['$event']) checkTouchEnd(event) {
this.start = event.changedTouches[0];
});

@HostListener('window:touchend', ['$event']) checkTouchEnd(event) {
 this.end = event.changedTouches[0];
 let scrollpositionValue;
 if((this.end.screenY - this.start.screenY) > 0) {
   console.log('scrolling up');
   console.log('[scroll-up]', this.end.screenY - this.start.screenY);
   scrollpositionValue = this.end.screenY - this.start.screenY;
  } else if(this.end.screenY - this.start.screenY < 0) {
   console.log('scrolling down');
   console.log('[scroll-down]', this.end.screenY - this.start.screenY);
   scrollpositionValue = this.end.screenY - this.start.screenY;
  }
 const scrollPosition = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
 console.log('[scroll]', scrollPosition);    
});

谁能帮我解决一下,我只想让移动浏览器上的 scrollY 位置滚动。

提前致谢!

My actual scenario is to show a specific div element when the other div element goes off from the screen when the screen is scrolled down.

不要为此使用滚动事件侦听器,为此使用 Intersection Observer (IO)

这是为此类问题设计的。使用 IO,您可以在 HTML 元素与另一个元素(或视口)相交时做出反应

Check this page,它向您展示了如何在元素进入视口后为其设置动画(一直向下滚动)

简要回顾一下您必须做的事情:

首先你必须创建一个新的观察者:

var options = {
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

这里我们定义,一旦您的目标元素在视口中 100% 可见(阈值为 1),您的回调函数就会被执行。在这里你可以定义另一个百​​分比,0.5 意味着一旦你的元素有 50% 可见,该函数就会被执行。

然后你必须定义要观看的元素

var target = document.querySelector('.div-to-watch');
observer.observe(target);

最后,您需要通过定义回调函数来指定当元素在您的视口中可见时应该发生什么:

var callback = function(entries, observer) { 
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // here you animate another element and do whatever you like
  });
};

如果您需要支持旧版浏览器,请使用 official polyfill from w3c.

如果您不想在元素再次滚动到视图中时再次触发动画,那么您 can also unobserve an element 一旦它被激活。