在项目中经常会遇到跳转到页面中的某个模块或者是做滚动到顶部、顶部等一系列操作,通常的做法是使用锚点或者是通过定时器慢慢移动距离等方法。锚点直接滚动没有动画效果,定时器需要写很多代码。效果并不是很好且繁琐。
经过多方面研究,发现css可以直接实现平滑滚动,下面就详细的分析一下。
scroll-behavior属性(
auto|smooth
):滚动框指定滚动行为及锚点。
auto:滚动框立即滚动。在线运行
scroll-behavior: auto;
效果图:
smooth:滚动框通过一个用户代理预定义的时长、使用预定义的时间函数,来实现平稳的滚动,用户代理应遵循其平台的约定,如果有的话。在线运行
scroll-behavior: smooth;
效果图:
完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="renderer" content="webkit" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
/>
<style>
.section-wrapper {
scroll-behavior: smooth;
height: 100vh;
overflow: auto;
}
#section-1 {
height: 100vh;
background: #f56c6c;
font-size: 40px;
}
#section-2 {
height: 100vh;
background: #67c23a;
font-size: 40px;
}
#section-3 {
height: 100vh;
background: #409eff;
font-size: 40px;
}
</style>
</head>
<body>
<div class="section-wrapper">
<section id="section-1">
<div>1</div>
<a href="#section-3">跳转的底部</a>
</section>
<section id="section-2">
<div>2</div>
</section>
<section id="section-3">
<div>3</div>
<a href="#section-1">返回的顶部</a>
</section>
</div>
</body>
</html>