我尝试了几乎所有在线可用的解决方案,但没有任何效果,以下是我尝试过的一些解决方案
我的实际场景是当屏幕向下滚动时另一个 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/