当滚动鼠标滑轮的时候,各个图层以不同的速度移动,形成视觉差的效果
background-attachment
作用是设置背景图像是否固定或者随着页面的其余部分滚动
值分别有如下:
- scroll:默认值,背景图像会随着页面其余部分的滚动而移动
- fixed:当页面的其余部分滚动时,背景图像不会移动
- inherit:继承父元素background-attachment属性的值
完成滚动视觉差就需要将background-attachment属性设置为fixed,让背景相对于视口固定。及时一个元素有滚动机制,背景也不会随着元素的内容而滚动
也就是说,背景一开始就已经被固定在初始的位置
核心的css代码如下:
section {
height: 100vh;
}
.g-img {
background-image: url(...);
background-attachment: fixed;
background-size: cover;
background-position: center center;
}
//background-attachment设置背景图像是否固定或者随着页面的其余部分滚动。
整体例子如下:
<!DOCTYPE html>
<html>
<head>
<title></title>
<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>
</head>
<body>
<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>
<script type="text/javascript">
</script>
</body>
</html>
网友评论