$(window).scroll 函数在移动设备上不起作用

Eya*_*ker 5 javascript jquery scroll

我在我的网站上使用 $(window).scroll 事件触发功能,一切都很好,只是它不适用于移动设备。

这是我正在使用的代码:

$(window).scroll(function(){
    var wh =  $(window).height();
    var scrolledFromtop = $(window).scrollTop();
    if( scrolledFromtop > wh ){

        $('html').addClass('scrolled');
    }else{
        $('html').removeClass('scrolled');
    }
});
Run Code Online (Sandbox Code Playgroud)

我也尝试了这段代码,但没有成功:

document.addEventListener("touchmove",aaa, false);
function aaa(){
    var wh =  $(window).height();
    var scrolledFromtop = $(window).scrollTop();
    if( scrolledFromtop > (wh) ){           
    $('html').addClass('scrolled');
    }

    else {
        $('html').removeClass('scrolled');
    }

};
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗?

Ada*_* M. 0

有些(?)移动浏览器在滚动完全停止之前不会触发该事件。

您可以尝试以下几种方法来解决此问题:

  1. 使用设置间隔
  2. 使用触摸事件
  3. 另一个解决方案是完全禁用本机滚动并使用 JavaScript 来模拟滚动。

$('window').on('touchmove', function(event) { //Prevent the window from being scrolled. event.preventDefault();

   //Do something like call window.scrollTo to mimic the scrolling
   //request the user made.
});
Run Code Online (Sandbox Code Playgroud)

您可以在这篇精彩的文章中找到更多相关信息:

http://tjvantoll.com/2012/08/19/onscroll-event-issues-on-mobile-browsers/