查看原文
其他

现代CSS:纯 CSS 实现平滑滚动

小懒 FED实验室 2024-02-12

“返回顶部” 功能是一个网页常用的功能之一,主要目的是用户浏览较长网页时,方便快速的回到页面顶部。之前我们可能首先想到的是 Javascript 来实现,尤其是 jQuery / Zepto 库流行的时候,实现起来还是比较方便的。

本文将介绍两个重要的现代 CSS 属性,用来实现平滑滚动效果:

  • position: sticky
  • scroll-behavior: smooth

1.效果预览

2.属性介绍

2.1.position: sticky

这种较新的位置值在 caniuse 上描述如下:

根据元素在视口中的显示方式,将其定位为 "fixed"或 "relative"。因此,在滚动时,必要时元素会被 "卡住"。

caniuse 数据的另一个重要注意事项是,您需要为其提供前缀,以获得最佳支持。我们的演示将回退到 position: fixed,这将实现主要目标,只是不那么优雅。

sticky 英文字面意思是粘,粘贴,所以可以称之为粘性定位。它是一个结合了 position:relative 和 position:fixed 两种定位功能于一体的特殊定位,适用于一些特殊场景。

元素先按照普通文档流定位,然后相对于该元素在流中的 flow root(BFC)和 containing block(最近的块级祖先元素)定位。而后,元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。这个特定阈值指的是 指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效,否则其行为与相对定位相同。

2.2.scroll-behavior: smooth

这是一个非常新的属性,支持率相对较低。这个确切的定义要求滚动行为(尤其是选择锚链接时)具有平滑的动画外观,而不是默认的更加生硬的瞬间跳转。

使用该属性可以实现 "渐进增强",这意味着浏览器支持该属性的用户可以获得更好的体验,而不支持该属性的浏览器也可以使用。

3.实现方案

3.1.页面框架搭建

小懒通过 html:5 快速创建页面框架,通过 header[id=top]+(main>(article+(div[class=back-to-top]>a[href=#top][class=back-to-top-link][aria-label="back to top"]))) 创建基础容器。你可能注意到 headerid 属性和 a 标签的 href 属性是同一个值,这里是想利用锚点功能,实现自动定位。与此同时,我们给 a 标签添加了 aria-label 属性,以提升标签的可访问性。

<header id="top">Header</header>
<main></main>
<div class="back-to-top">
<a href="#top" class="back-top-top-link" aria-label="back to top"></a>
</div>

定义基本的样式:

:root {
--headerH: 80px;
}
body,header,main,footer { margin: 0; padding: 0}
header {
display: flex;
height: var(--headerH);
background-color: #ccc;
justify-content: center;
align-items: center;
}
main {
position: relative;
background-color: #ff0;
padding: 10px;
text-align: justify;
}
.back-to-top {
position: absolute;
top: 100vh;
right: 0.25rem;
bottom: -5em;
width: 3em;
pointer-events: none;
& a {
position: fixed;
position: sticky;
top: calc(100vh - 5rem);
display: block;
width: 40px;
height: 40px;
border: 1px solid #ccc;
text-decoration: none;
text-align: center;
line-height: 40px;
background-color: #fff;
pointer-events: all;
}
}

点击TOP 元素,整体滚动效果是瞬移,体验不是太好,效果如下:

3.2.增加平滑滚动

/* Smooth scrolling IF user doesn't have a preference due to motion sensitivities */
@media screen and (prefers-reduced-motion: no-preference) {
html {
scroll-behavior: smooth;
}
}

prefers-reduced-motion CSS 媒体功能用于检测用户是否在其设备上启用了设置,以尽量减少非必要的动态效果。该设置用于向设备上的浏览器传达用户偏好移除、减少或替换基于动作的动画的界面。

4.最后

纯 CSS 实现的平滑滚动效果比较简单,如果需要实现复杂的动画逻辑,还是需要借助 JavaScript 的能力来实现。总之,适合自己需求的才是最好的。


大家都在看

关注下方公众号,定期抽奖读者福利多多
继续滑动看下一个

现代CSS:纯 CSS 实现平滑滚动

小懒 FED实验室
向上滑动看下一个

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存