jQuery scrollTop not working in Chrome but working

2019-01-06 14:37发布

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 without smooth animation) after I made some changes.

But it is still working smoothly in Firefox. What could be wrong?

Here is the jQuery function I used,

jQuery:

$('a#gotop').click(function() {
    $("html").animate({ scrollTop: 0 }, "slow");
    //alert('Animation complete.');
    //return false;
});

HTML

<a id="gotop" href="#">Go Top </a>

CSS

#gotop {
      cursor: pointer;
      position: relative;
      float: right;
      right: 20px;
      /*top:0px;*/
}

15条回答
做个烂人
2楼-- · 2019-01-06 14:39

I use:

var $scrollEl = $.browser.mozilla ? $('html') : $('body');

because read jQuery scrollTop not working in Chrome but working in Firefox

查看更多
戒情不戒烟
3楼-- · 2019-01-06 14:41
 $("html, body").animate({ scrollTop: 0 }, "slow");

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

 html, body {
         overflow-x: hidden;        
    }
查看更多
趁早两清
4楼-- · 2019-01-06 14:44

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");).

查看更多
smile是对你的礼貌
5楼-- · 2019-01-06 14:45
// if we are not already in top then see if browser needs html or body as selector
var obj = $('html').scrollTop() !== 0 ? 'html' : 'body';

// then proper delegate using on, with following line:
$(obj).animate({ scrollTop: 0 }, "slow");

BUT, best approach is to scroll an id into your viewport using just native api (since you scroll to top anyway this can be just your outer div):

document.getElementById('wrapperIDhere').scrollIntoView(true);
查看更多
Deceive 欺骗
6楼-- · 2019-01-06 14:47

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

查看更多
做自己的国王
7楼-- · 2019-01-06 14:49

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

This works for me in chrome.

查看更多
登录 后发表回答