jQuery scrollTop not working in Chrome but working in Firefox

后端 未结 15 1787
再見小時候
再見小時候 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: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");).

提交回复
热议问题