当用户点击链接时,如何在转到其他页面之前滚动到顶部?

时间:2015-04-23 08:17:19

标签: javascript jquery css animation scroll

我正在尝试在我的网站上创建平滑的页面转换,以便用户在单击指向其他页面的链接时不会感觉到“页面加载”。我想要的两个例子是minimalissimo.comdefringe.com。当您在这些网站的任何页面上单击指向其他文章的链接时,该页面会在下一页开始加载之前动画滚动到顶部。

到目前为止,我有以下代码:

jQuery(document).ready(function($){

  $back_to_top = $('.link-to-article');

  $back_to_top.on('click', function(){
    $("html, body").animate({scrollTop:0},260);
  });

});

以上代码不起作用,单击该类的链接时不会发生滚动;但是,如果我使用prevent default,那么页面会滚动到顶部,但当然下一页没有打开,因为使用preventDefault禁用链接。

如果您能提供帮助,请与我们联系。 谢谢。

2 个答案:

答案 0 :(得分:5)

你是正确的,你需要使用preventDefault,但是你需要在动画完成后手动重定向:

$back_to_top.on('click', function(){
   var href = $(this).attr('href');
   $(document.body).animate({scrollTop:0}, 260, function() {
      window.location.href = href;
   });
   return false;
});

答案 1 :(得分:1)

jQuery(document).ready(function ($) {
    $back_to_top = $('.link-to-article');

    $back_to_top.on('click', function (e) {
        e.preventDefault();
        $this = $(this);
        $("html, body").animate({
            scrollTop: 0
        }, 260, function() {
            window.location.href = $this.attr('href');
        });
    });
}(jQuery));