jQuery scrollTop not working in Chrome but working in Firefox

后端 未结 15 1685
再見小時候
再見小時候 2020-11-29 02:54

I have used a scrollTop function in jQuery for navigating to top, but strangely \'the smooth animated scroll\' stopped working in Safari and Chrome (scrolling w

相关标签:
15条回答
  • 2020-11-29 03:36
     $("html, body").animate({ scrollTop: 0 }, "slow");
    

    This CSS conflict with scroll to top so take care of this

     html, body {
             overflow-x: hidden;        
        }
    
    0 讨论(0)
  • Testing on Chrome, Firefox and Edge, the only solution that worked fine for me is using setTimeout with the solution of Aaron in this way:

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

    No one of the other solutions resetted the previuos scrollTop, when I reloaded the page, in Chrome and Edge for me. Unfortunately there is still a little "flick" in Edge.

    0 讨论(0)
  • 2020-11-29 03:38

    I don't think the scrollTop is a valid property. If you want to animate scrolling, try the scrollTo plugin for jquery

    http://plugins.jquery.com/project/ScrollTo

    0 讨论(0)
  • 2020-11-29 03:44

    Scroll body and check if it worked:

    function getScrollableRoot() {
        var body = document.body;
        var prev = body.scrollTop;
        body.scrollTop++;
        if (body.scrollTop === prev) {
            return document.documentElement;
        } else {
            body.scrollTop--;
            return body;
        }
    }
    
    
    $(getScrollableRoot()).animate({ scrollTop: 0 }, "slow");
    

    This is more efficient than $("html, body").animate because only one animation used, not two. Thus, only one callback fires, not two.

    0 讨论(0)
  • 2020-11-29 03:46

    Try using $("html,body").animate({ scrollTop: 0 }, "slow");

    This works for me in chrome.

    0 讨论(0)
  • 2020-11-29 03:47

    A better way to solve this problem is to use a function like this:

    function scrollToTop(callback, q) {
    
        if ($('html').scrollTop()) {
            $('html').animate({ scrollTop: 0 }, function() {
                console.log('html scroll');
                callback(q)
            });
            return;
        }
    
        if ($('body').scrollTop()) {
            $('body').animate({ scrollTop: 0 }, function() {
                console.log('body scroll');
                callback(q)
            });
            return;
        }
    
        callback(q);
    }
    

    This will work across all browsers and prevents FireFox from scrolling up twice (which is what happens if you use the accepted answer - $("html,body").animate({ scrollTop: 0 }, "slow");).

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