CSS平滑滚动效果实现方法
一、纯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)