长话短说,在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>
答案 0 :(得分:1)
实际上,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中存在相同的问题。
答案 1 :(得分:1)
这是我经过一段时间的修补后想出的解决方法。 希望这会有所帮助!
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>
答案 2 :(得分:0)
在子元素上使用 scroll-snap-stop: always;。