我如何 运行 jQuery 仅在用户没有滚动时才起作用?

How can I run jQuery function only if user hasn’t scrolled?

我一直在尝试在我的网站上加入自动滚动功能 (live here)。我希望它在加载后 6 秒滚动到内容,但前提是用户位于页面的最顶部并且没有滚动到足以发现#introduction 元素。

我有这段代码,它可以工作,但如果用户已经自己滚动了,我不希望它执行:

$('html,body').delay(6000).animate({
    scrollTop: $('#introduction').offset().top
}, 1000);

如果可能的话,我也希望它能以一种缓入缓出的方式发生。

你可以这样做:

$('html')
  .delay(6000)
  // If the user has scrolled down, do nothing. Otherwise scroll to element
  .queue(function(next) {
    if ($(window).scrollTop() > 0) {
      return;
    } else {
      next();
    }
  })
  .animate(
    {
      scrollTop: $('#introduction').offset().top,
    },
    1000,
    'swing',
  );

至于 ease-in-out 动画,您需要 JqueryUIswinglinear 是 Jquery 库支持的缓动函数。