如何使用 jQuery 平滑滾動到頁面部分
對於單頁模板和網站,在單擊錨鏈接時滾動到頁面部分是一種常見的做法。這是一個小的 jQuery hack,當訪問者單擊導航菜單中的錨鏈接(或頁面上的任何其他位置)時,我經常使用它來平滑滾動到頁面部分。調整滾動速度值1000
到任何你想要的速度。該值以毫秒為單位。
$(document).on('click', 'a[href^="#"]', function (e) {
e.preventDefault();
$('html, body').stop().animate({
scrollTop: $($(this).attr('href')).offset().top
}, 1000, 'linear');
});
下面是導航和部分的 HTML 標記的樣子:
<nav>
<a href="#features">Features</a>
<a href="#faq">FAQ</a>
<a href="#pricing">Pricing</a>
</nav>
<!--main container-->
<div class="container">
<!--feature section-->
<section id="features">...</section>
<!--faq section-->
<section id="faq">...</section>
<!--pricing section-->
<section id="pricing">...</section>
</div>
不想使用 jQuery?您也可以使用 vanilla JavaScript 進行平滑滾動,但它可能不適用於舊瀏覽器:
document.querySelectorAll('a[href^="#"]').forEach($anchor => {
$anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth',
block: 'start' //scroll to top of the target element
});
});
});
也不是原生 JavaScript 的忠實粉絲?這是純 CSS 3 解決方案,但它只適用於最新的瀏覽器:
html {
scroll-behavior: smooth;
}