【问题标题】:Detect document scrolling on mobile without touch event在没有触摸事件的情况下检测移动设备上的文档滚动
【发布时间】:2021-12-01 15:50:18
【问题描述】:

我正在尝试在我正在处理的网站上实现一种效果,当用户垂直滚动时,一个元素会水平滑动相对量(即,如果用户向下滚动文档高度的 10%,则特定元素将向左移动其自身宽度的 10%)。

我遇到的问题是我使用touchstarttouchend 事件来计算用户垂直滚动了多少。但是,在移动设备(例如 iPhone)上,在用户完成滑动并停止触摸屏幕后,文档会继续滚动一小会儿。

是否有替代方法来检测移动设备上的文档滚动,包括触摸事件结束后滚动的距离?

谢谢!

我的代码:

            var wave = $('.front-page__mobile-wave');
            var height = $(document).height();
            var width = wave.width();
            var oneWidth = width/100;
            var ts;

            $(document).bind('touchstart', function (e){
                ts = e.originalEvent.touches[0].clientY;
             });

            $('.front-page').bind('touchmove', function(e){
                var te = e.originalEvent.changedTouches[0].clientY;
                var scroll = $(window).scrollTop();
                var percentHeight = scroll / height * 100;
                var bgSlideForward = oneWidth * percentHeight;
                var bgSlideBack = -oneWidth * percentHeight;
                if(ts < te){
                    wave.css('left', bgSlideBack);
                } else if (ts > te){
                    wave.css('left', -bgSlideForward);
                }
            });

【问题讨论】:

  • 您是否尝试过使用window.pageYOffset
  • 感谢 @yuuuu 帮助我找到答案!

标签: javascript jquery scroll touch


【解决方案1】:

解决方案是使用scroll 事件而不是touchstarttouchmove,并使用变量来跟踪当前与以前的scrollTop,即:

            var wave = $('.front-page__mobile-wave');
            var height = $(document).height();
            var width = wave.width();
            var oneWidth = width/100;
            var lastScrollTop = 0;
            $(window).scroll(function(e){
                var scroll = $(window).scrollTop();
                var percentHeight = scroll / height * 100;
                var bgSlideForward = oneWidth * percentHeight;
                var bgSlideBack = -oneWidth * percentHeight;
                if(scroll > lastScrollTop){
                    wave.css('left', bgSlideBack);
                } else if (scroll < lastScrollTop){
                    wave.css('left', -bgSlideForward);
                }
                lastScrollTop = scroll;
            });

【讨论】:

    猜你喜欢
    • 2020-12-09
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    相关资源
    最近更新 更多