简体   繁体   中英

scrollTo() and jquery scrollTop() not working in Chrome

I am making a puzzle platformer using html elements as obstacles. Some levels I want to start at the bottom of the document. So I tried using

$(document).ready(function() {
    $(document).scrollTop($(document).height() - $(window).height());
}

and

$(document).ready(function() {
    window.scrollTo(0, document.body.scrollHeight);
}

they both work perfectly fine in Firefox but neither work in Chrome. I only could get it to work when animating the scroll which will not work for what I am trying to do.

edit: I am not using jQuery.toScroll() I tried vanilla toScroll and jQuery.scrollTop()

Browsers attach their scrollbars to the page differently. Use $('html,body').scrollTop(). You should also use $(window).innerHeight(). Like this...

 $('html,body').scrollTop($(document).height() - $(window).innerHeight()); //Or to smooth scroll it $('html,body').animate({ scrollTop: $(document).height() - $(window).innerHeight() }, 1000); 

Note: $(document).height() will return the same value as $(window).innerHeight() if the document is shorter than the window.

I did not execute full testing but I'm also experiencing the issue via Developer Tools at least on a specific jQuery version and latest Chrome. animate does work. scrollTop and scrollTo do both not work. Nonetheless even if you explicitly said that you not want to use animate I still recommend it as it is working and I see no reason of not using it if you use it like this:

$('html, body').animate({scrollTop: 500}, 0);

This will scroll to 500px and has no animation at all because the duration is set to 0. I also have to point on a previous issue with Chrome:

Possible duplicate

Issue on Github

I know the issue is closed but it might be relevant and probably it should be reported because there is something fishy.

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