javascript - Angular 8 窗口滚动事件不会在移动浏览器上触发

标签 javascript angular scroll window-scroll

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

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

我可以在台式机/笔记本电脑上执行此操作,但不能在滚动事件根本不触发的移动设备上执行此操作。

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

@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);    
});

有人可以帮我解决方案吗,我想要的只是让移动浏览器上的滚动位置滚动。

提前致谢!

最佳答案

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 元素与另一个元素(或与视口(viewport))相交,您就可以使用react

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

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

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

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

var observer = new IntersectionObserver(callback, options);

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

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

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

最后,您需要通过定义回调函数来指定元素在视口(viewport)中可见后应发生的情况:

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.

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

关于javascript - Angular 8 窗口滚动事件不会在移动浏览器上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60649692/

相关文章:

javascript - 如何在特定组件(如 Html 和 css)中导入 javascript 文件?

angular - RxJS 库中是否存在安全问题?

iphone - 如何滚动到 UITableView 中的特定单元格(由其标签确定)

javascript - 带有颜色选择器 Eyecon 的 Android Webview

javascript - 在 JavaScript 双 for 循环中更新 HTML 进度条?

angular - 如何为垫卡添加垫分页器?

javascript - 向右滚动对象

javascript - 使用构造函数获取已定义对象的名称

javascript - 为什么在参数传递期间不计算 JavaScript 哈希对象?

iphone - UISearchBar 在 UITableView 滚动时滚动