Owl Carousel横向滚动页面点击切换按钮后需定位至顶部
Fix: Scroll to Top After Owl Carousel Page Switch
我明白你遇到的问题了——点击页面底部的切换按钮后,新页面直接定位到了底部,而不是我们期望的顶部区域。这是因为Owl Carousel的URLhashListener机制会默认让浏览器滚动到哈希对应的元素位置,而你的切换按钮刚好在页面底部,所以跳转后就停在了底部位置。
解决方案
我们可以利用Owl Carousel的translated事件,在轮播切换完成后,强制将页面滚动到顶部。这个事件会在每一次轮播动画结束后触发,刚好适合用来修正滚动位置。
修改后的完整代码
HTML
<link href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"/> <link href="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/assets/owl.theme.default.min.css" rel="stylesheet"/> <script src="https://owlcarousel2.github.io/OwlCarousel2/assets/vendors/jquery.min.js"></script> <script src="https://owlcarousel2.github.io/OwlCarousel2/assets/owlcarousel/owl.carousel.js"></script> <div class="owl-carousel owl-theme"> <div class="page one" data-hash="page1"> Button at the bottom! <a href="#page2" class="linkB">Page 2</a> </div> <div class="page two" data-hash="page2"> Button at the bottom! <a href="#page1" class="linkA">Page 1</a> <a href="#page3" class="linkB">Page 3</a> </div> <div class="page three" data-hash="page3"> Button at the bottom! <a href="#page2" class="linkA">Page 2</a> </div> </div>
CSS
.owl-carousel { position: relative; } .page { padding: 1rem; height: 1500px; } .one { background: #bec4bd; } .two { background: green; } .three { background: #41253c; } .linkA { position: absolute; bottom: 10px; left: 10px; text-decoration: none; background: red; color: #fff; padding: 5px 15px; margin-right: 5px; font-family: sans-serif; font-size: 14px; } .linkB { position: absolute; bottom: 10px; right: 10px; text-decoration: none; background: red; color: #fff; padding: 5px 15px; margin-right: 5px; font-family: sans-serif; font-size: 14px; }
JavaScript
$('.owl-carousel').owlCarousel({ items: 1, autoplay: false, loop: false, nav: false, dots: false, center: true, mouseDrag: false, touchDrag: false, autoHeight: true, margin: 10, smartSpeed: 500, URLhashListener: true, autoplayHoverPause: true, startPosition: 'URLHash' }).on('translated.owl.carousel', function() { // 切换完成后滚动到页面顶部 $('html, body').scrollTop(0); // 或者用原生JS实现平滑滚动:window.scrollTo({top: 0, behavior: 'smooth'}); });
关键修改说明
- 给Owl Carousel实例添加了
translated.owl.carousel事件监听,这个事件在轮播的滑动动画完全结束后触发 - 在事件回调里,调用
$('html, body').scrollTop(0)强制页面滚动到顶部,这样不管切换按钮在页面哪个位置,新页面都会从顶部开始显示 - 如果你想要平滑滚动的过渡效果,可以把代码换成原生JS的
window.scrollTo({top: 0, behavior: 'smooth'})
内容的提问来源于stack exchange,提问作者vishnu
相关产品推荐
相关产品推荐

