一、純CSS實現方案
- 使用 scroll-behavior 屬性
屬性值
- auto (默認值):滾動框立即滾動
- smooth:滾動框以平滑的方式滾動
/* 全局平滑滾動 */
html {scroll-behavior: smooth;
}/* 特定容器平滑滾動 */
.scroll-container {scroll-behavior: smooth;overflow-y: scroll;height: 300px;
}
<!DOCTYPE html>
<html>
<head>
<style>html {scroll-behavior: smooth;}section {height: 100vh;padding: 20px;}#section1 { background-color: #f9c1d5; }#section2 { background-color: #b8e0f6; }#section3 { background-color: #d5f9c1; }
</style>
</head>
<body><nav><a href="#section1">Section 1</a><a href="#section2">Section 2</a><a href="#section3">Section 3</a></nav><section id="section1"><h2>第一部分</h2></section><section id="section2"><h2>第二部分</h2></section><section id="section3"><h2>第三部分</h2></section>
</body>
</html>
高級用法
- 控制滾動速度
雖然scroll-behavior: smooth本身不提供速度控制,但可以結合CSS過渡實現:
html {scroll-behavior: smooth;scroll-snap-type: y proximity;scroll-padding-top: 50px; /* 為固定導航欄留出空間 */
}
- 水平平滑滾動
.horizontal-scroll {scroll-behavior: smooth;overflow-x: auto;white-space: nowrap;
}
- 禁用特定元素的平滑滾動
.no-smooth-scroll {scroll-behavior: auto !important;
}
二 window.scrollTo()
window.scrollTo() 是 JavaScript 中用于控制窗口滾動位置的方法,它可以實現即時滾動和平滑滾動兩種效果。
// 基本形式
window.scrollTo(x-coord, y-coord)// 選項對象形式(支持平滑滾動)
window.scrollTo(options)