为什么平滑滚动在滚动之前会闪烁?

11

我正在构建一个单页网站,通过锚点分成不同的部分。当你点击导航链接时,它会平滑地滚动到该部分(只完成了资金区域和关于我们),但是,有大约50%的时间,当你点击链接时,它要滑动到的背景图像会在jQuery向上或向下滚动之前闪烁。

对我来说,似乎HTML正在尝试立即转到锚点,因此会出现闪烁,但是然后jQuery会说:“等一下,我需要缓慢滚动。”

我不确定如何解决这个问题。

jQuery:

// SlowScroll Funding Areas
$(document).ready(function(){

// 'slowScrollTop' is the amount of pixels #teamslowScroll
// is from the top of the document

    var slowScrollFunding = $('#funding-areas').offset().top;

// When #anchor-aboutus is clicked

    $('#anchor-funding-areas').click(function(){
        // Scroll down to 'slowScrollTop'
        $('html, body, #home-wrap').animate({scrollTop:slowScrollFunding}, 1000);
    });
});

// SlowScroll About Us
$(document).ready(function(){
// 'slowScrollTop' is the amount of pixels #slowScrollTop
// is from the top of the document

    var slowScrollTop = $('#about-us').offset().top + 446;

// When #anchor-aboutus is clicked

$('#anchor-aboutus').click(function(){
    // Scroll down to 'slowScrollTop'
    $('html, body, #aboutus-wrap').animate({scrollTop:slowScrollTop}, 1000);
});
});

我非常感激所有的建议。

2个回答

10

在您的点击函数后尝试添加event.preventDefault();

这将阻止链接执行其应该执行的操作(立即跳转到锚点),并防止竞态条件。


5
$('#anchor-aboutus').click(function(){
  // Scroll down to 'slowScrollTop'
  $('html, body, #aboutus-wrap').animate({scrollTop:slowScrollTop}, 1000);
  event.preventDefault();
  event.stopPropagation();
});

甚至更干净的是:

$('#anchor-aboutus').click(function(){
  // Scroll down to 'slowScrollTop'
  $('html, body, #aboutus-wrap').animate({scrollTop:slowScrollTop}, 1000);
  return false;
});

这是为什么:

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接