移动端虚拟滚动Feed中DOM变更时snap scroll异常问题求助
移动端Snap Scroll+虚拟滚动的DOM变更异常问题
我的移动端Web应用有一个垂直滚动的图片Feed,采用原生snap scroll实现,同时搭配虚拟滚动器(仅在DOM中保留X个元素,按需移除/插入上下方元素)。但滚动过程中触发DOM变更时,出现两个异常:
- 切换到下一张图片时,上一张图片闪烁
- Feed滚动回之前浏览过的图片(非100%复现)
我制作了一个复现示例,每0.5秒向DOM中添加一个div,切换到移动端视图滚动即可复现上述问题。
复现代码
HTML
<div class="snap-scroll-container"></div>
JavaScript
const snapScrollContainer = document.querySelector(".snap-scroll-container"); [ "https://media.istockphoto.com/photos/gray-british-cat-kitten-picture-id1086004080?k=20&m=1086004080&s=612x612&w=0&h=tvQKNjBGIsfCmUPR8YVJYfjLrTZ9JINbisKRjMj87IY=", "https://images.unsplash.com/photo-1595433707802-6b2626ef1c91?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80", "https://images.unsplash.com/photo-1592194996308-7b43878e84a6?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80", "https://images.unsplash.com/photo-1574144611937-0df059b5ef3e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=764&q=80", "https://www.warrenphotographic.co.uk/photography/bigs/08483-Ginger-kitten-portrait.jpg", "https://img.freepik.com/premium-photo/kitten-portrait-beautiful-fluffy-gray-kitten-cat-animal-baby-british-blue-kitten-with-big-eyes-sits-beige-plaid-looking-camera-blue-background_221542-1665.jpg?w=740", "https://libreshot.com/wp-content/uploads/2018/02/cute-kitten-portrait-861x1292.jpg", "https://www.warrenphotographic.co.uk/photography/bigs/35147-Portrait-of-tabby-kitten-8-weeks-old.jpg", ].forEach((src) => { const image = document.createElement("img"); const div = document.createElement("div"); div.setAttribute("class", "snap-scroll-child"); image.setAttribute("src", src); div.appendChild(image); snapScrollContainer.appendChild(div); }); const addEmptyDiv = () => { const div = document.createElement("div"); div.innerHTML = "bla"; snapScrollContainer.appendChild(div); } setInterval(addEmptyDiv, 500);
CSS
body { margin: 0; padding: 0; } .snap-scroll-container { scroll-snap-type: y mandatory; height: 100vh; overflow-y: scroll; } .snap-scroll-child { scroll-snap-stop: always; scroll-snap-align: end; } img { object-fit: cover; height: 100vh; width: 100vw; }
已尝试方案及顾虑
由于性能要求,无法放弃虚拟滚动器。查阅相关资料后,仅找到两个可行但不理想的方案:
- 用JS实现snap scroll(不愿采用)
- 延迟DOM变更至滚动结束(非最优解)

内容的提问来源于stack exchange,提问作者Gilad Bar
相关产品推荐
相关产品推荐

