CSS scroll-snap滚动超出首尾div无法回弹问题如何解决?
当在div之间滚动时,snap-scroll功能运行正常,但如果持续向下滚动,页面会滚动到最后一个div之外,反之持续向上滚动时会滚动到第一个div之外。
预期效果为页面不能滚动超出首尾div范围,而是应该回弹到首尾div位置。
该问题可在Chrome、Brave、Edge、Opera浏览器复现,Safari和Firefox中不存在。
问题原因
这是Chromium内核浏览器的特有表现:根元素默认启用了滚动溢出(overscroll)效果,滚动到内容边界时允许超出范围实现拉动手感,此时scroll-snap规则不会触发边界位置的吸附回弹。
解决方案
方案1:单CSS属性修复(改动最小)
直接在html的样式规则中添加overscroll-behavior-y: none,禁用根元素的纵向滚动溢出效果即可。
修改后的CSS片段:
html { scroll-snap-type: y mandatory; overscroll-behavior-y: none; /* 新增此行 */ } body { margin: 0; } div { width: 100vw; height: 100vh; scroll-snap-align: start; }
该方案无需修改页面结构,仅新增一行代码即可解决问题。
方案2:内部滚动容器方案(兼容性更好)
如果需要保留页面其他区域的滚动溢出效果,可以将滚动容器从根元素替换为自定义的内部容器,滚动边界会自然限制在容器内部,不会出现超出范围的问题。
完整实现代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } .scroll-wrapper { width: 100vw; height: 100vh; overflow-y: auto; scroll-snap-type: y mandatory; } .page-item { width: 100%; height: 100vh; scroll-snap-align: start; } </style> </head> <body> <div class="scroll-wrapper"> <div class="page-item"></div> <div class="page-item"></div> <div class="page-item"></div> </div> <script> const colors = ["red", "green", "blue"]; document.querySelectorAll(".page-item").forEach((div, index) => { div.style.backgroundColor = colors[index]; }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Vinay Sharma
相关产品推荐
相关产品推荐

