滚动行为已损坏



所以之前我写了一小段代码来实现网页上的平滑滚动。起初它工作得很好,但随着开发的进展,它随机停止了工作,此后就再也没有开始工作。现在,当它滚动时,从你按下按钮开始会有一个延迟,然后它最终会捕捉到页面的目标部分。

这是库的脚本标签:

<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll@15.0.0/dist/smooth-scroll.polyfills.min.js"></script>

这是javascript:

const scroll = new SmoothScroll('nav a[href*="#"]',{
speed: 800
});

我不想使用CSSscroll-behavior: smooth,因为我的大多数网站流量都在Safari上,Safari不支持这种功能。

对于不支持滚动行为属性的浏览器,您可以使用JavaScript或JavaScript库(如jQuery(来创建适用于所有浏览器的解决方案:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").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
});
});
</script>

最新更新