sroll-snap-type制作全屏滚动

以前制作大屏上下滚动的网页时(一次滚动一屏),我们得借助js控制,或者使用第三方插件,比如fullpage.js或者swiper.js等,现在只需要两个css样式就可以完成这个效果。

直接看代码,想看效果,直接复制下面的代码。预览链接

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			body{
     
     
			 margin:0
			}
            .father {
     
     
                scroll-snap-type: y mandatory;
                height: 100vh;
                overflow: auto;
            }
            .child {
     
     
                scroll-snap-align: start;
                background-color: #3388FF;
                height: 100%;
            }
            .child:nth-child(2n){
     
     
                background-color: #0078A8;
            }
         </style>
	</head>
	
	<body>
        <section class='father'>
            <section class='child'>111</section>
            <section class='child'>222</section>
            <section class='child'>333</section>
            <section class='child'>444</section>
            <section class='child'>555</section>
        </section>
	</body>
</html>

语法

scroll-snap-type

可以控制滚动条停留位置,它常用的有两个属性mandatory 与 proximity

mandatory :强制的停留在scroll-snap-align所指定的位置,常用这个属性
proximity:字面意是接近,这个属性会让滚动条停留在scroll-snap-align所指定的位置的附近或者指定位置

scroll-snap-type: y mandatory 中的 y 表示捕捉 y 轴方向上的滚动

同理scroll-snap-type: x mandatory 中的 x 表示捕捉 x 轴方向上的滚动

scroll-snap-align

设置子元素的对其方式

start:对其顶部
end:对其底部
center:对其中间

scroll-padding和scroll-margin

如果需要对滚动位置做偏移控制,可以使用这两个属性,让子元素默认停留位置做适当偏移

scroll-padding作用于父元素
scroll-margin作用于子元素

scroll-padding用法如下

.father {
    
    
    scroll-snap-type: y mandatory;
    height: 100vh;
    overflow: auto;
    /**离盒子顶部100px停留**/
    scroll-padding-top:100px;
}

scroll-margin用法如下

.child {
    
    
    scroll-snap-align: start;
    background-color: #3388FF;
    height: 100%;
    /**离盒子顶部100px停留**/
    scroll-margin-top:100px;
}

兼容性

IE10以上都是兼容的,放心用

猜你喜欢

转载自blog.csdn.net/dan_seek/article/details/112567210