可滚动面板捕捉到滚动上的元素

在用户滚动时,可滚动div内部是否有一种方法可以捕捉到元素。

例如,如果我们有CSS,如

.container { height: 300px; width: 200px; overflow: auto } li { height: 40px; width: 100 % ; } 

和HTML一样

 
  • test
  • test
  • test
  • test
  • test
  • test
  • test
  • test
  • test
  • test
  • test
  • test
  • test
  • 因此容器应该有一个垂直滚动条。 当用户滚动时我希望它能够在它们停止滚动时最终滚动位置将容器滚动位置捕捉到所示的最近的div。 这可能很难,因为像safari这样的浏览器也提供了动力,因此它必须是滚动结束时的事件。

    任何想法,如果这是可能的,以及如何。

    奇妙

    您可以使用setTimeout。 这应该工作

     var snap_timer; var scroll_from_mouse = true; function snapList(){ var snapped = false; var i = 0; while(!snapped && i < $('.container li').size()){ var itop = $('.container li').eq(i).position().top; var iheight = $('.container li').eq(i).outerHeight(); if(itop < iheight && itop > 0){ scroll_from_mouse = false; snapped = true; var new_scroll_top = 0; if(iheight - itop > iheight / 2) new_scroll_top = $('.container').scrollTop() + itop; else if(i > 1) new_scroll_top = $('.container').scrollTop() - ($('.container li').eq(i-1).outerHeight() - itop); else new_scroll_top = 0; $('.container').scrollTop(new_scroll_top); } i++; } }; $(function(){ $('.container').scroll(function(){ clearTimeout(snap_timer); if(scroll_from_mouse) snap_timer = setTimeout(snapList, 200); scroll_from_mouse = true; }); }); 

    您可以使用CSS Scroll Snap

    但是,该function现已弃用,因此如果您想考虑跨浏览器的vanilla javascript重新实现本机CSS Scroll Snap规范,如下所述: 如何在Chrome中模拟CSS Scroll Snap Points? ,你可以使用我写的这个库

    使用它而不是原生css解决方案的主要原因是它适用于所有现代浏览器,并且具有可自定义的配置,以允许在转换和滚动检测中进行自定义计时。

    该库使用vanilla javascript缓动函数重新实现css捕捉function,并使用容器元素的scrollTop / scrollLeft属性和滚动事件侦听器的值工作。

    这是一个显示如何使用它的示例:

     import ScrollSnap from 'scroll-snap' const snapConfig = { scrollSnapDestination: '90% 0%', // scroll-snap-destination css property, as defined here: https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-destination scrollTimeout: 100, // time in ms after which scrolling is considered finished scrollTime: 300 // time in ms for the smooth snap } function callback () { console.log('called when snap animation ends') } const element = document.getElementById('container') const snapObject = new ScrollSnap(element, snapConfig) snapObject.bind(callback) // unbind the element // snapObject.unbind(); 

    你可以在这里看到一个有效的演示