javascript - 仅在向下滚动时捕捉滚动到元素

标签 javascript jquery scroll

我遇到了一个问题,需要您的指导。当我结束在页面上滚动(鼠标滚轮和触控板)时,我愿意执行动画。

当我停止滚动时,窗口应该捕捉到最近的元素,并且仅当窗口顶部距离该元素小于 100px 时才如此。

我尝试过使用任何插件,例如 fullpage.js、snapscroll 和 skrollr,它们的核心包中集成了此功能,但是它不符合我的需求,因为它们都没有关于该功能的适当文档。滚动方向或滚动量本身。

我一直在尝试包含上述条件,但没有成功:

  • 向上或向下滚动方向
  • 捕捉发生的固定金额

这是我的 HTML 结构:

<div class="section" id="section-1">
  content here
</div>
<div class="section" id="section-2">
  content here
</div>
<div class="section" id="section-3">
  content here
</div>
<div class="section" id="section-4">
  content here
</div>

这是我到目前为止的 jQuery 脚本:

var items = $(".section");
var animating = false;
var lastScrollTop = 0;

$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
      // downscroll code
      console.log('We are scrolling down!');
      clearTimeout($.data(this, 'scrollTimer'));
      if (!animating) {
        $.data(this, 'scrollTimer', setTimeout(function() {
          items.each(function(key, value) {
             animating = true;
             $('body').animate({
                scrollTop: $(value).offset().top + 'px'
             }, 250);
             setTimeout(function() {
                animating = false;
             }, 300);
           return true;
        });
      }, 1200));
    };
} else {
  console.log('We are scrolling down!');
}
  lastScrollTop = st;
});

提前致谢

最佳答案

我希望这就是您正在寻找的

var timeout = 1200;
var timer;
$(window).scroll(function(event){
    clearTimeout(timer);
    timer = setTimeout(function() {
        $(".section").each(function() {
            var scrollTop = $(window).scrollTop();
            var offset = $(this).offset().top;
            if(offset-scrollTop < 100 && offset-scrollTop > -100) {
                $('html,body').animate({scrollTop: $(this).offset().top},'slow');
                return;
            }
        });
    }, timeout);
});

JSfiddle

关于javascript - 仅在向下滚动时捕捉滚动到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33871956/

相关文章:

javascript - 使用 jQuery 更改 SharePoint 中的 application.master 页面

javascript - 判断已经滚动到底部的d​​iv的id

javascript - Jquery/Javascript 无法在 Firefox 上运行。为什么?

javascript - 如何在angularjs中为递归模板创建行选择器

javascript - 在 JavaScript 中实现回调

javascript - 在 Ember.js 中将一个模板加载到另一个模板中

javascript - 在 VueJS 2 和 JSX 中将展开运算符与事件监听器结合使用

javascript - CORS:为什么我的浏览器不发送 OPTIONS 预检请求?

javascript - 如何从 future 的函数调用中清除以前的变量

javascript - 使用 jQuery 调整元素滚动的 CSS 不透明度