视差滚动(Parallax Scrolling)是指多层背景以不同的速度移动,形成立体的运动效果,带来非常出色的视觉体验
我们可以把网页解刨成:背景层、内容层、悬浮层
当滚动鼠标滑轮的时候,各个图层以不同的速度移动,形成视觉差的效果
使用css
形式实现视觉差滚动效果的方式有:
作用是设置背景图像是否固定或者随着页面的其余部分滚动
值分别有如下:
完成滚动视觉差就需要将background-attachment
属性设置为fixed
,让背景相对于视口固定。及时一个元素有滚动机制,背景也不会随着元素的内容而滚动
也就是说,背景一开始就已经被固定在初始的位置
核心的css
代码如下:
section {
height: 100vh;
}
.g-img {
background-image: url(...);
background-attachment: fixed;
background-size: cover;
background-position: center center;
}
整体例子如下:
<style>
div {
height: 100vh;
background: rgba(0, 0, 0, .7);
color: #fff;
line-height: 100vh;
text-align: center;
font-size: 20vh;
}
.a-img1 {
background-image: url(https://images.pexels.com/photos/1097491/pexels-photo-1097491.jpeg);
background-attachment: fixed;
background-size: cover;
background-position: center center;
}
.a-img2 {
background-image: url(https://images.pexels.com/photos/2437299/pexels-photo-2437299.jpeg);
background-attachment: fixed;
background-size: cover;
background-position: center center;
}
.a-img3 {
background-image: url(https://images.pexels.com/photos/1005417/pexels-photo-1005417.jpeg);
background-attachment: fixed;
background-size: cover;
background-position: center center;
}
</style>
<div class="a-text">1</div>
<div class="a-img1">2</div>
<div class="a-text">3</div>
<div class="a-img2">4</div>
<div class="a-text">5</div>
<div class="a-img3">6</div>
<div class="a-text">7</div>
同样,让我们先来看一下两个概念transform
和perspective
:
3D
视角示意图如下所示:
举个例子:
<style>
html {
overflow: hidden;
height: 100%
}
body {
/* 视差元素的父级需要3D视角 */
perspective: 1px;
transform-style: preserve-3d;
height: 100%;
overflow-y: scroll;
overflow-x: hidden;
}
#app{
width: 100vw;
height:200vh;
background:skyblue;
padding-top:100px;
}
.one{
width:500px;
height:200px;
background:#409eff;
transform: translateZ(0px);
margin-bottom: 50px;
}
.two{
width:500px;
height:200px;
background:#67c23a;
transform: translateZ(-1px);
margin-bottom: 150px;
}
.three{
width:500px;
height:200px;
background:#e6a23c;
transform: translateZ(-2px);
margin-bottom: 150px;
}
</style>
<div id="app">
<div class="one">one</div>
<div class="two">two</div>
<div class="three">three</div>
</div>
而这种方式实现视觉差动的原理如下:
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8