我该如何在移动iOS设备上启用平滑滚动,webkit-overflow-scroll
无法正常工作?
我该如何在移动iOS设备上启用平滑滚动,webkit-overflow-scroll
无法正常工作?
很遗憾,在OSX和iOS上原生的Safari浏览器无法实现平滑滚动。但是有一些JavaScript polyfills可以实现这一功能,例如:https://github.com/iamdustan/smoothscroll。您需要使用JavaScript来初始化它,而不是CSS。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
JS
$(document).ready(function(){
// Add smooth scrolling to all links with the class scroll
$("a.scroll").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
HTML
<a class="scroll" href="#">Text</a>
所以我使用了smoothscroll-polyfill解决了这个问题,它可以在移动iOS上使我的页面平滑滚动。
使用下一个CDN来进行polyfill。
<script src="https://cdnjs.cloudflare.com/ajax/libs/iamdustan-smoothscroll/0.4.0/smoothscroll.min.js"></script>
对于任何想要自定义/增强平滑滚动并支持基本上任何现代浏览器(包括Safari / Safari for iOS)的人,您可以查看我编写的此API。
与标准的polyfill相比,它允许使用自定义缓动函数,在x和y轴上同时平滑滚动多个元素,中断滚动动画等等。
您可以在这里找到更多信息。