jQuery 跨浏览器“滚动到顶部",带动画 [英] jQuery cross-browser "scroll to top", with animation

查看:25
本文介绍了jQuery 跨浏览器“滚动到顶部",带动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用这个:

$('#go-to-top').each(function(){
  $(this).click(function(){ 
    $('html').animate({ scrollTop: 0 }, 'slow'); return true; 
  });
});

这在 Chrome 中不起作用,而在 Opera 中我得到一个小闪烁:浏览器立即滚动到顶部,然后回到底部,然后它开始缓慢地滚动回到顶部,就像它应该的那样.

which doesn't work in Chrome, and in Opera I get a small flicker: the browser instantly scrolls to the top, then back to the bottom and then it begins to scroll slowly back to top, like it should.

有没有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

您正在从 click 函数返回 true,因此它不会阻止默认浏览器行为(即导航到 truecode>go-to-top 锚点.正如马克所说,使用:

You're returning true from the click function, so it won't prevent the default browser behaviour (i.e. navigating to thego-to-top anchor. As Mark has said, use:

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

所以你的代码现在应该是这样的:

So your code should now look like:

$('#go-to-top').each(function(){
    $(this).click(function(){ 
        $('html,body').animate({ scrollTop: 0 }, 'slow');
        return false; 
    });
});

这篇关于jQuery 跨浏览器“滚动到顶部",带动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆