[前端] css scroll-snap控制滚动元素的实现

1823 0
黑夜隐士 2023-2-25 10:42:45 | 显示全部楼层 |阅读模式
scroll-snap解释

    让网页容器滚动停止的时候,自动平滑定位到指定元素的指定位置
scroll-snap应用条件

    容器必须可滚动
应用场景

    轮播图全屏滚动图
使用解析

MDN详情
滚动容器

sroll-snap-type:none | [ x | y | block | inline | both ] [ mandatory | proximity ]?
    定义在滚动容器中的一个临时点(snap point)如何被严格的执行
  • 规定了一个容器是否对内部滚动动作进行捕捉,并且规定了如何去处理滚动结束状态
      x:滚动容器只捕捉其水平轴上的捕捉位置。block:滚动容器仅捕捉到其块轴上的捕捉位置。inline:滚动容器仅捕捉到其内联轴上的捕捉位置。mandatory:强制滚动到某个定位元素proximity:短距离滑动可能会定位到某个元素,也可能就停在滚动位置

一般使用:

scroll-snap-type: x mandatory;scroll-padding:定义滚动盒子的padding
注意正常的padding在scroll-snap中用来控制停止后相对滚动容器的位置会失效
scroll-snap-stop: normal | always
控制停止元素的行为,normal根据滚动距离计算要停止的元素,always:无视滚动距离,只会停止在下一个元素,比如滑动1000px还是停止在下一个元素
子元素

scroll-snap-align:start | center | end;
滚动停止后,元素所在的位置,类比justify-content 属性的 flex-start | flex-end | center
下面三个分别对应start | center | end,表示滚动结束后元素停止容器开头、中心、结尾


scroll-margin:定义某个子元素的margin
用于精细控制滚动停止后元素相对于滚动容器的位置

<ul class="snap">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  ...
</ul>  

.snap {
    overflow-x: auto;
    scroll-snap-type: y mandatory;
    scroll-padding-top: 30px;
}

li {
    scroll-snap-align: start;
}


代码示例:
<!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>Document</title>
    <style>
        .section {
            height: 200px;
            width: 400px;
            display: flex;
            overflow-x: auto;
            scroll-snap-type: x mandatory;

        }

        .section__item {
            /* scroll-snap-align: start; */
            height: 200px;
            width: 200px;
            margin: 0 100px;
            flex: none;
            scroll-padding-right: 40px;
            scroll-snap-align: end;
        }

        .section__item:nth-child(odd) {
            background: red;
        }

        .section__item:nth-child(even) {
            background: green;
        }
    </style>
</head>

<body>
    <div class="section">
        <div class="section__item">Item 1</div>
        <div class="section__item">Item 2</div>
        <div class="section__item">Item 3</div>
        <div class="section__item">Item 4</div>
        <div class="section__item">Item 5</div>
    </div>

    <script>
    </script>
</body>

</html><font face="Tahoma"><span style="white-space: normal;"> </span></font>到此这篇关于css scroll-snap控制滚动元素的实现的文章就介绍到这了,更多相关css scroll-snap控制滚动元素内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章,希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行