【问题标题】:How to avoid recursion calling scrollIntoView() in scroll event-handler?如何避免在滚动事件处理程序中递归调用 scrollIntoView()?
【发布时间】:2020-04-06 20:48:23
【问题描述】:

我想将我的网站分成几个屏幕大小的部分,并在用户开始滚动时自动滚动到下一个部分。为了实现它,我编写了这样的代码:

$(window).scroll(function() {
    getElementToScroll().scrollIntoView({behavior: "smooth"});
}

但是调用scrollIntoView() 会导致递归。我怎样才能避免这个问题?也许还有另一种更合适的方式将元素滚动到视图中?

附:流畅的行为是必要的。

【问题讨论】:

    标签: javascript jquery recursion scroll


    【解决方案1】:

    您可以使用CSS Scroll Snap 来实现此行为。它不需要 JavaScript,只需要 CSS。在撰写本文时,除了 IE 和 Edge 之外,大多数浏览器都拥有此 API 的 full support

    检查下面的示例以查看它的实际效果。

    html,
    body,
    .container{
      width: 100%;
      height: 100%;
    }
    
    .container {
      scroll-snap-type: y mandatory;
      overflow-y: scroll;
    }
    
    section {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 10em;
      width: 100%;
      scroll-snap-align: start;
      scroll-snap-stop: always
    }
    
    section:first-of-type {
      background: red;
    }
    
    section:nth-of-type(2) {
      background: orange;
    }
    
    section:nth-of-type(3) {
      background: yellow;
    }
    
    section:nth-of-type(4) {
      background: green;
    }
    
    section:nth-of-type(5) {
      background: blue;
    }
    
    section:nth-of-type(6) {
      background: purple;
    }
    <article class="container">
      <section>First section</section>
      <section>Second section</section>
      <section>Third section</section>
      <section>Fourth section</section>
      <section>Fifth section</section>
      <section>Sixth section</section>
    </article>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2014-08-03
      • 1970-01-01
      • 2023-04-07
      • 2011-04-04
      相关资源
      最近更新 更多