如何 - 平滑滾動
學習如何使用 CSS 建立平滑滾動效果。
平滑滾動
第二部分
點選我平滑滾動到上方第一部分平滑滾動
向 <html> 元素新增 scroll-behavior: smooth
可為整個頁面啟用平滑滾動(注意:也可以將其新增到特定元素/滾動容器)
瀏覽器支援
表格中的數字表示完全支援 scroll-behavior 屬性的第一個瀏覽器版本。
屬性 | |||||
---|---|---|---|---|---|
scroll-behavior | 61.0 | 79.0 | 36.0 | 14.0 | 48.0 |
跨瀏覽器解決方案
對於不支援 scroll-behavior
屬性的瀏覽器,你可以使用 JavaScript 或 JavaScript 庫(如 jQuery)來建立適用於所有瀏覽器的解決方案。
示例
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// 為所有連結新增平滑滾動
$("a").on('click', function(event) {
// 確保在覆蓋預設行為之前 this.hash 有值
if (this.hash !== "") {
// 阻止預設的錨點點選行為
event.preventDefault();
// 儲存 hash
var hash = this.hash;
// 使用 jQuery 的 animate() 方法新增平滑頁面滾動
// 可選的數字 (800) 指定滾動到指定區域所需的時間(毫秒)
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// 滾動完成後將 hash (#) 新增到 URL(預設點選行為)
window.location.hash = hash;
});
} // 結束 if
});
});
</script>
自己動手試一試 »
提示: 在我們的 CSS 參考文件中瞭解更多關於 scroll-behavior 屬性的資訊:CSS scroll-behavior 屬性。