如何解决移动端Chrome浏览器的scroll-snap反向吸附问题?
移动端Chrome Scroll-Snap反向吸附问题
问题背景
我正在开发一个包含三个全屏页面的网站,支持页面间平滑滚动。为了让页面在地址栏显示/隐藏时都保持全屏高度,我采用了动态计算--vh变量的方案,但这导致滚动时(尤其是地址栏切换显示状态时)页面高度频繁变化,进而引发问题:在移动端Chrome中,从第3页向上滚动到第2页,或从第2页向上滚动到第1页时,偶尔会出现反向scroll-snap吸附(本该向上吸附到上一页,结果反而向下吸附到下一页)。
代码实现
JavaScript
let vh = window.innerHeight * 0.01; document.documentElement.style.setProperty('--vh', `${vh}px`); window.addEventListener('resize', () => { let vh = window.innerHeight * 0.01; document.documentElement.style.setProperty('--vh', `${vh}px`); }); window.addEventListener('touchmove', () => { let vh = window.innerHeight * 0.01; document.documentElement.style.setProperty('--vh', `${vh}px`); }); // Constants book = document.querySelector(".book"); scrollbar = document.querySelector("#scrollbar"); // Scrollbar book.addEventListener("scroll", () => { // setTimeout(function(){ // alert(scrollbar.style.height); // }, 5000); scrollbar.style.top = (window.innerHeight * book.scrollTop / book.scrollHeight).toString() + "px"; scrollbar.style.height = (window.innerHeight * window.innerHeight / book.scrollHeight).toString() + "px"; });
CSS
* { box-sizing: border-box; margin: 0; padding: 0; } body { height: 100vh; height: calc(var(--vh, 1vh) * 100); width: 100%; overflow: hidden; } .book { height: 100vh; height: calc(var(--vh, 1vh) * 100); width: 100%; position: absolute; overflow-y: scroll; overflow-x: hidden; /* Scrolling */ overflow-y: scroll; scroll-snap-type: y mandatory; scroll-behavior: smooth; } .page { height: 100vh; height: calc(var(--vh, 1vh) * 100); width: 100%; /* Scrolling */ scroll-snap-align: start; scroll-snap-stop: always; } .book::-webkit-scrollbar { width: 0px; } #p1 { background-color: lightblue; } #p2 { background-color: lightcyan; } #p3 { background-color: lightgray; } /* Insert Custom Scrollbar */ #scrollbar { /* Sizing */ height: 33.3vh; height: calc(var(--vh, 1vh) * 33.3); width: 6px; /* Layout */ position: absolute; top: 0%; right: 0%; /* Visual */ background-color: black; border-radius: 1px; }
HTML
<!-- Home Page --> <!DOCTYPE html> <!-- Header --> <html lang="en"> <head> <!-- Metadata --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- CSS --> <link rel="stylesheet" href="index.css"> </head> <body> <article class="book"> <section class="page" id="p1"> </section> <section class="page" id="p2"> </section> <section class="page" id="p3"> </section> </article> <div id="scrollbar"></div> <script src="resize.js"></script> </body> </html>
寻求建议
曾参考过相关的Scroll-Snap故障问题,但无法适配其解决方案,现寻求针对性的技术建议来修复该反向吸附问题。
内容的提问来源于stack exchange,提问作者Robin Aldabanx
相关产品推荐
相关产品推荐

