jQuery scrollTop() does not work in scrolling DIV on mobile browsers, alternatives?

前端 未结 13 960
傲寒
傲寒 2020-12-08 19:52

I am trying to scroll to a specific location in a scrolling DIV. Right now I am using a pixel offset with the jQuery scrollTop() function which works great on desktop brows

相关标签:
13条回答
  • 2020-12-08 20:13

    Use the following code:

    $("body").animate( { scrollTop: 50,  },  800,  function(){
        $("body").clearQueue();
    } );
    
    0 讨论(0)
  • 2020-12-08 20:14

    Temporarily setting the overflow property to 'hidden', as recommended in @Allan Nienhuis' answer, does not work on Android 4.0.3, for instance (which is, e.g., what the Kindle Fire 2s are running) - when you set overflow back to scroll, the element scrolls back to the top.

    Alternatives:

    • Roll your own scrolling via a helper function, as demonstrated here - while this is simple to implement, it is bare-bones in that it doesn't give you inertial scrolling or overscrolling.

    • Use a library such as iScroll, which implements its own, sophisticated scrolling (inertial, overscrolling) based on CSS transformations.

    Using iScroll requires a bit of setup, though: you need a wrapper div with fixed height and style overflow: hidden and the element to scroll should have no overflow style. This jsFiddle demo shows how it's done.

    0 讨论(0)
  • 2020-12-08 20:15

    This worked for me:

    setTimeout( function() {
        $(div).scrollTop(0)
    }, 500 );
    
    0 讨论(0)
  • 2020-12-08 20:15

    rather than using the scroll, scrollTo, or scrollTop methods (which give me problems in mobile), I recommend setting an ID on your top DOM element (like #top), and just using:

    document.getElementById("top").scrollIntoView();
    

    that works the best for me so far across all devices and browsers.

    0 讨论(0)
  • 2020-12-08 20:19

    I found the answer here http://blog.jonathanargentiero.com/jquery-scrolltop-not-working-on-mobile-devices-iphone-ipad-android-phones/

    Mobile phones doesn't understand $('html,body') so u can do the following for mobile

    if(navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {           
        window.scrollTo(0)
    } else {
        // default `$('html,body')` code for scrolling
    }
    

    OR

    simply use $('body') instead of $('html, body').

    0 讨论(0)
  • 2020-12-08 20:20

    The only way i could achieve scrolling to the top of the page on a Galaxy Tab was hiding the page body for 100ms while scrolling. Using jQuery:

    $("body").hide();
    window.scrollTo(0, 0);
    setTimeout(function(){ $("body").show() }, 100);
    
    0 讨论(0)
提交回复
热议问题