前面讲过一个页面的回弹效果,用的是js来写的大多数,今天用纯css来实现这一效果
scroll-snap-type: y mandatory;
scroll-snap-align: center;
主要用到css这俩属性,具体了解可参考mdn解释
scroll-snap-align - CSS: Cascading Style Sheets | MDN
scroll-snap-type - CSS: Cascading Style Sheets | MDN
效果如下:
代码如下:
<!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>
/* setup */
html,
body,
.holster {
height: 100%;
width: 100%;
}
.container {
overflow: auto;
outline: 1px dashed lightgray;
width: 100%;
}
.container > div {
text-align: center;
scroll-snap-align: center;
}
.container.y {
width: 100%;
height: 100%;
}
.y.mandatory-scroll-snapping {
scroll-snap-type: y mandatory;
}
.y.container > div {
font-size: 128px;
width: 100%;
height: 100%;
}
/* appearance fixes */
.y.container > div:first-child {
height: 100%;
font-size: 64px;
}
/* coloration */
.container > div:nth-child(even) {
background-color: #87ea87;
}
.container > div:nth-child(odd) {
background-color: #87ccea;
}
.word {
height: 100%;
width: 100%;
overflow: auto;
}
.child {
height: 1000px;
}
</style>
</head>
<body>
<div class="holster">
<div class="container y mandatory-scroll-snapping" dir="ltr">
<div>图片</div>
<div class="word">
<div class="child">我是内容哈哈哈</div>
</div>
</div>
</div>
</body>
</html>
不仅仅是y轴可以,x轴也可以有这种效果:
代码如下:
<!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>
/* setup */
html,
body,
.holster {
height: 100%;
width: 100%;
}
.container {
overflow: auto;
outline: 1px dashed lightgray;
width: 100%;
}
.container > div {
text-align: center;
scroll-snap-align: center;
}
.container.x {
width: 100%;
height: 200px;
display: flex;
}
/* scroll-snap */
.x.mandatory-scroll-snapping {
scroll-snap-type: x mandatory;
}
.x.container > div {
font-size: 64px;
width: 100%;
height: 200px;
flex: none;
}
/* coloration */
.container > div:nth-child(even) {
background-color: #87ea87;
}
.container > div:nth-child(odd) {
background-color: #87ccea;
}
</style>
</head>
<body>
<div class="holster">
<div class="container x mandatory-scroll-snapping" dir="ltr">
<div>X 1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</div>
</body>
</html>