jQuery scrollTop() does not work in scrolling DIV

2019-01-23 01:39发布

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 browsers but it does not work on android mobiles browsers with the exception of Google's Chrome Android browser (do not have an iOS device to test if that works). All the solutions I have found are for page (window) scrolling and not for scrolling in a DIV, anyone have any suggestions on what else I can use to accomplish the same task?

Here is a example:
http://jsfiddle.net/aQpPc/
http://jsfiddle.net/aQpPc/embedded/result/

Other things I have tried that work in desktop browsers:

document.getElementById('ID_of_element_in_a_DIV').scrollIntoView();
document.getElementById('ID_of_DIV').scrollTop = 200;

EDIT 3/11/13:

This is a know android browser issue: https://code.google.com/p/android/issues/detail?id=19625

One user in the bug report suggested a workaround:

because the issue only seems to appear when the overflow property is set to scroll, you can first set it to 'hidden', set the scrollTop property, then reset it back to 'scroll' (or auto). The scrollTop property seems to be honored when the element is re-rendered with scrollbars. It's not clear if this has any unexpected side-effects, but "it works on my machine!"

11条回答
Luminary・发光体
2楼-- · 2019-01-23 02:32

A workaound that worked for me: first, temporarily set the overflow property to 'hidden', then set the scrollTop property, then set the overflow property back to 'scroll' (or auto). The scrollTop value seems to be kept intact and honored when the overflow property is set back to 'scroll'. This was a pretty trivial workaround that worked on all browsers I tested on (desktop and mobile). I didn't test it exhaustively, and I didn't test with transitions in place, so there may be side-effects that I haven't encountered... Your mileage may vary - but it's an easy thing to try.

查看更多
等我变得足够好
3楼-- · 2019-01-23 02:35

This worked for me:

setTimeout( function() {
    $(div).scrollTop(0)
}, 500 );
查看更多
神经病院院长
4楼-- · 2019-01-23 02:35

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').

查看更多
疯言疯语
5楼-- · 2019-01-23 02:38

Did you try this ?

$("html").scrollTop(0);
查看更多
太酷不给撩
6楼-- · 2019-01-23 02:38

Try using jQuery's .animate method:

$('.div').animate({ scrollTo: x; });

Where x is equal to the position of the div you want to scroll to the top of.

查看更多
登录 后发表回答