滑动页面效果(scroll snap)

2,543 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

水平或者竖直滑动页面效果,滑动过程中随着页面接近上端或者下端会有一种吸附的感觉,如果我们接到这个任务,在以前可能就会挠头,因为要实现这样滑动带吸附感的效果的确不容易,需要大量 JavaScript 代码,还需要一些算法算距离。

CSS Scroll Snap是CSS中一个独立的模块,可以让网页容器滚动停止的时候,自动平滑定位到指定元素的指定位置,包含scroll-*以及scroll-snap-*等 CSS 属性。

今天先简单地开个头

准备工作

创建一个文件夹命名 scroll_to_snap 作为项目,然后下这个文件夹下创建 index.html 和 style.css 文件。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll to Snap</title>
</head>
<body>
    <div class="container">
        <section>
            <h1>Page One</h1>
        </section>
        <section>
            <h1>Page Two</h1>
        </section>
        <section>
            <h1>Page Three</h1>
        </section>
    </div>
</body>
</html>
body{
    width: 100vw;
    height: 100vh;
    margin: 0;
    background-color: blue;
}

上面 css 代码也就是让 body 布满浏览器整个窗口,让 body 元素的宽度和高度为窗口的大小,默认 margin 是有一定大小,这里将其设置为 0。效果如下

scroll_to_snap_001.png

body .container{
    width: 100%;
    height: 100%;
    background-color: orange;
    margin: 0;
}

scroll_to_snap_002.png

通过 flex 进行对 section 中内容进行对齐。通常在做将内容居中都会采用下面 css 组合来实现。

.container section{
    display: flex;
    justify-content: center;
    align-items: center;
}

屏幕快照 2021-09-29 下午6.57.12.png

.container section{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
}

简单地对每个 section 进行配色,给一个背景色和文本颜色。

.container section:nth-child(1){
    background-color: orange;
    color: blue;
}

.container section:nth-child(2){
    background-color: olive;
    color: blue;
}

.container section:nth-child(3){
    background-color: orchid;
    color: blue;
}
  • 给文字添加一些效果,调整字体和文字大小。
.container section h1{
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12em;
}

屏幕快照 2021-09-29 下午7.06.47.png

竖直滑动效果

上面那些都是准备工作,现在才真正进入到 scroll snap 仅仅 3 行代码我们就能实现一个不错的竖直方向的滑动效果。作用在滚动容器上,

body .container{
    width: 100%;
    height: 100%;
    margin: 0;
    scroll-snap-type: y mandatory;
}

作用在你希望有滚动定位点的子元素上

.container section{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
    scroll-snap-align: start;
}

水平滑动效果

body .container{
    width: 100%;
    height: 100%;
    margin: 0;
    scroll-snap-type: x mandatory;
    overflow-x: scroll;
    display: flex;
}

.container section{
    flex: none;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
    scroll-snap-align: start;
}