jQuery跨浏览器"滚动到顶部",带有动画

Ale*_*lex 19 javascript jquery scroll jquery-effects jquery-animate

现在我正在使用这个:

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

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

有一个更好的方法吗?

Ben*_*enM 80

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

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

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

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

  • "每个人"绝对是不必要的.即使有多个id为go-to-top的元素,那么单击`click`将超过所需! (3认同)

Mar*_*man 5

为了让它在歌剧中运作,这个答案证明是有帮助的.

把它与你的 click()

$(this).click(function() {
    $(window.opera ? 'html' : 'html, body').animate({
        scrollTop: 0
    }, 'slow');
});
Run Code Online (Sandbox Code Playgroud)

关于jsfiddle的代码示例.

旁注如果您正在使用的.each()是分配一个单击处理程序,您不需要迭代该集合,它可以简化为:

$('#go-to-top').click(function(){ 
    $(window.opera ? 'html' : 'html, body').animate({
        scrollTop: 0
        }, 'slow');
});
Run Code Online (Sandbox Code Playgroud)

此外,如果有多个带ID #go-to-top的元素,您的标记将无效,请尝试将其切换为类.go-to-top