繁体   English   中英

如何仅在用户未滚动时运行 jQuery 函数?

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

我一直在尝试在我的网站上加入自动滚动功能(住在这里)。 我希望它在加载后 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动画,你需要JqueryUI swinglinear是 Jquery 库支持的缓动函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM