Listening to all scroll events on a page

后端 未结 4 958
借酒劲吻你
借酒劲吻你 2021-02-07 02:39

Background:

I\'m writing a component that opens up a sub-menu on click. I can\'t know where this component will be placed on the page or how far it will

相关标签:
4条回答
  • 2021-02-07 02:58

    How about listing on all elements and the window?

    $('*').add(window).scroll(function() {
        console.log('scroll');
    });
    
    0 讨论(0)
  • 2021-02-07 02:59

    You should be able to attach a document-level listener with a third parameter of true to capture the scroll events on all elements. Here's what that looks like:

    document.addEventListener('scroll', function(e){ }, true);
    

    The true at the end is the important part, it tells the browser to capture the event on dispatch, even if that event does not normally bubble, like change, focus, and scroll.

    Here's an example: http://jsbin.com/sayejefobe/1/edit?html,js,console,output

    0 讨论(0)
  • 2021-02-07 03:00

    The best way to do it would be to find out which elements are scrollable, then attach listeners to them. You could run this function on any page change to make sure you've always got all the scrollables.

    This is a benefit over using listeners on every element (as the other solutions would do) in terms of performance: every time the page updates so do the listeners. With lots, this quickly affects performance and memory use.

    The updated fiddle: http://jsfiddle.net/ArtOfCode/wAadt/8/

    The code:

    $("*").each(function() {
        if($(this).css("overflow") == "auto" || $(this).css("overflow") == "scroll") {
            $(this).scroll(function() {
                console.log("scroll");
            });
        }
    });
    

    (thanks to @pebbl for the help)

    You could then wrap this in a function and run it on change:

    function addListeners() {
        $("*").each(function() {
            if($(this).css("overflow") == "auto" || $(this).css("overflow") == "scroll") {
                $(this).css('border', '1px solid red').scroll(function() {
                    console.log("scroll");
                });
            }
        });
    }
    
    $("body").on("change",function()
        addListeners();
    }
    

    Admittedly it is a bit convoluted but it addresses the issue with as few event listeners as possible.

    0 讨论(0)
  • 2021-02-07 03:10

    You need to see whether scroll is happening to window level or to an element level. Usually in your case '*' should suffice.

    $('*').scroll(function() {
        alert('scroll');
    });
    

    Here is updated link: http://jsfiddle.net/wAadt/1

    0 讨论(0)
提交回复
热议问题