检测用户是否滚动超过20像素(无论页面在页面上的何处) [英] Detect if user scrolls more than 20px no matter where it's on the page

查看:88
本文介绍了检测用户是否滚动超过20像素(无论页面在页面上的何处)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以检测用户在页面上的任何位置滚动了20px以上?

Is it possible to detect if the user scrolls more than 20px wherever it's on the page??

我的意思是,在一页设计中,当用户滚动超过20px时不仅要从文档顶部滚动,还需要删除一个类.

I mean, in a one page design, I need to remove a class when the user scrolls more than 20px but not only from the top of the document.

每次打开一个弹出窗口时,都会向有问题的弹出窗口添加一个类,一旦用户滚动,我想删除该类.

Each time he opens a popup, a class is added to the popup in question, once the user scrolls, I would like to remove this class.

无论此功能在页面上的什么位置,都重复此功能.

Repeat this function no matter where it's on the page.

我当前的代码:

$(window , 'body').on('scroll', function() {
    $('.navbar-collapse').collapse('hide');
    $("#wrapper").removeClass('newsletter-opened');
        $("#newsletter").removeClass('opened');
});

谢谢!

推荐答案

您可以为此使用jQuery.

You can use jQuery for that.

使用我的解决方案,如果用户在您进入页面时滚动200像素,或者滚动到顶部或底部且滚动的像素数最少为20像素,那么您的更改就会被调用.

With my solution, if user has scroll 200px when he come on your page if he scroll to top or bottom with minumum 20px of scroll your changes was called.

var userScroll = $(document).scrollTop();

$(window).on('scroll', function() {
   var newScroll = $(document).scrollTop();
   if(userScroll - newScroll > 20 || newScroll - userScroll > 20){
      $('.navbar-collapse').collapse('hide');
      $("#wrapper").removeClass('newsletter-opened');
      $("#newsletter").removeClass('opened');
   }
}

查看您的jsFiddle之后,我知道您想要什么,只需检查一下即可:

After look your jsFiddle, i know what you want, just check that :

仅在启用弹出框时定义滚动,并且仅在弹出框具有类opened

Just define the scroll at the moment when popin is enable and make your job only when the popin has class opened

$(document).ready(function(){   
    $("a.open-newsletter").on( "click", function() {
        $("#newsletter").toggleClass('opened');
        userScroll = $(document).scrollTop();
        return false;
    });

    $(window , 'body').on('scroll', function() {
        if ( $("#newsletter").hasClass('opened') ) {
            var newScroll = $(document).scrollTop();
            if (userScroll - newScroll > 100 || newScroll - userScroll > 100) {
                $("#newsletter").removeClass('opened');
            }
        }
    });
});

这篇关于检测用户是否滚动超过20像素(无论页面在页面上的何处)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆