滚动捕捉 CSS 跳过元素

Scroll snap CSS skipping elements

长话短说,在 Chrome (81.0.4044.138) 上,出于某种原因,滚动捕捉会跳过 中间 <div class="item2">。在 Firefox (76.0.1) 上运行良好。知道为什么吗?

 html {
      scroll-snap-type: y mandatory;
    }
    
    body {
      margin: 0;
      padding: 0;
      overflow-x: hidden;
      overflow-y: scroll;
    }
    
    div {
      height: 100vh;
      scroll-snap-align: center;
    }
    
    .item1 {
      background-color: blue;
      font-size: 5rem;
    }
    
    .item2 {
      background-color: yellow;
      font-size: 5rem;
    }
    
    .item3 {
      background-color: red;
      font-size: 5rem;
    }
<body class="container">
        <div class="item1">Hello World</div>
        <div class="item2">Hello World</div>
        <div class="item3">Hello World</div>
    </body>

实际上,chrome 浏览器中有一个关于它的错误 (其背后的原因,直到现在还不清楚,所以没有人知道为什么)。所以你不能直接将 scroll-snap-type 应用到你的 html 标签(同时将它应用到 body 也不起作用)标签。因此,为了使其正常工作,您应该创建另一个 div 并将您的元素包裹在其中。

所以试试这个:

body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.container {
  scroll-snap-type: y mandatory;
  overflow-y: scroll;
}

div {
  height: 100vh;
  scroll-snap-align: center;
}

.item1 {
  background-color: blue;
  font-size: 5rem;
}

.item2 {
  background-color: yellow;
  font-size: 5rem;
}

.item3 {
  background-color: red;
  font-size: 5rem;
}
<body>
  <div class="container">
    <div class="item1">Hello World</div>
    <div class="item2">Hello World</div>
    <div class="item3">Hello World</div>
  </div>
</body>

注意: CSS-tricks 中的相同问题。

在子元素上使用 scroll-snap-stop: always;

这是我经过一段时间修改后想出的解决方法。 希望这对您有所帮助!

const scrollContainer = document.querySelector('.container')

// don't forget to add "scroll-behavior: smooth;" to the .container CSS

scrollContainer.onwheel = function(event) {
  // use scrollBy using the deltaY just as a direction
  // the exact value is not important because of "scroll-snap-type: y mandatory;"
  scrollContainer.scrollBy(0, event.deltaY);

  // this will stop the original scroll event.
  return false;
};
body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.container {
  scroll-snap-type: y mandatory;
  scroll-behavior: smooth;
  overflow-y: scroll;
}

div {
  height: 100vh;
  scroll-snap-align: center;
}

.item1 {
  background-color: blue;
  font-size: 5rem;
}

.item2 {
  background-color: yellow;
  font-size: 5rem;
}

.item3 {
  background-color: red;
  font-size: 5rem;
}
<body>
  <div class="container">
    <div class="item1">Hello World</div>
    <div class="item2">Hello World</div>
    <div class="item3">Hello World</div>
  </div>
</body>