简体   繁体   中英

How do I detect whether scroll events are fired *only once* like on touch devices?

iOS devices (and likely Android ones) have a different scrolling behavior: The scroll event is only fired once after the entire scroll is done.

How do I detect whether the browser behaves this way?

I could use window.Touch or Modernizr.touch but they don't tell me anything about the scroll behavior, it would be like asking if someone is French to understand whether they like croissants, right? :)

I think you're right about the detection because there will be some devices that will support both touch and mouse behaviors (like Windows 8 tablets), some will only support touch (phones) and some will only support mouse (desktops). Because of that, I don't think you can conclusively say that a device only has one behavior as some could have both.

Assuming that what you're really trying to do is to figure out whether you should respond immediately to every scroll event or whether you should use a short delay to see where the scroll destination ends up, then you could code a hybrid effect that could work well in either case.

var lastScroll = new Date();
var scrollTimer;
window.onscroll = function(e) {

    function doScroll(e) {
        // your scroll logic here
    }

    // clear any pending timer
    if (scrollTimer) {
        clearTimeout(scrollTimer);
        scrollTimer = null;
    }

    var now = new Date();
    // see if we are getting repeated scroll events
    if (now - lastScroll < 500){
        scrollTimer = setTimeout(function() {
            scrollTimer = null;
            doScroll(e);
        }, 1000);
    } else {
        // last scroll event was awhile ago, so process the first one we get
        doScroll(e);
    }
    lastScroll = now;
};

doScroll() would be your scroll processing logic.

This gets you a hybrid approach. It always fires on the first scroll event that arrives when there hasn't recently been a scroll event. If there are a series of scroll events, then it fires on the first one and then waits until they stop for a second.

There are two numbers that you may want to tweak. The first determines how close scroll events must be to consider them rapid fire from the same user action (current set to 500ms). The second determines how long you wait until you process the current scroll position and assume that the user stopped moving the scrollbar (currently set to 1s).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM