偶然从某站上看到一个视差演示的小demo,于是照着视频做了一个测试。
主要是用来实现滚动视差的,可以当做新人练手,大致代码参考如下:
效果展示
HTML5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>滚动视差演示</title>
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<div class="content">
<h2>三国演义</h2>
<p>背景视差效果演示</p>
</div>
<div class="parallex p1"><h3>赵云</h3></div>
<div class="content">
<p>
赵云(公元168年-公元229年),字子龙,琅琊阳都(今山东临沂)人,三国时期蜀汉名将。他是刘备的重要将领,也是蜀汉五虎上将之一。
</p>
<p>
赵云年轻时曾在吴郡任职,后来投靠了刘备。他以勇猛善战而闻名,被誉为“龙的传人”。赵云曾参与多次重要战役,如长坂坡之战、赤壁之战、汉中之战等,表现出色,立下了许多战功。
</p>
</div>
<div class="parallex p2"><h3>关羽</h3></div>
<div class="content">。。。</div>
<div class="parallex p3"><h3>马超</h3></div>
<div class="content">。。。</div>
</body>
</html>
CSS
* {
margin: 0;
padding: 0; /* 清除浏览器默认样式 */
}
body {
background-color: #2b333e; /* 设置页面背景颜色 */
}
.parallex {
width: 100%;
height: 80vh; /* vh表示的是视图宽高,1vh表示占网页视图的1% */
/* border: 5px solid black; */
position: relative;
overflow: hidden;
background-repeat: no-repeat;
background-position: top center;
background-size: cover;
background-attachment: fixed; /* 当页面滚动时,背景图会固定 */
}
.p1 {
background-image: url(1.png);
}
.p2 {
background-image: url(2.png);
}
.p3 {
background-image: url(3.png);
}
.content {
/* width: 960px; */
height: 40vh;
margin: 0 auto;
text-align: center; /* 文字向两侧对齐,对最后一行无效 */
display: flex; /* 悬浮 */
align-items: center; /* 可以简单理解为垂直页面居中 */
justify-content: center; /* 定义浏览器如何沿着容器分配元素和周围内容空间 */
flex-direction: column; /* 以列进行悬浮 */
}
/* 大标题是h2,小标题是h3 */
h2 {
font-size: 45px;
letter-spacing: 10px;
text-align: center;
color: white;
font-weight: 400;
font-family: '楷体';
}
h3 {
font-size: 45px;
letter-spacing: 10px;
text-align: center;
color: white;
font-weight: 400;
line-height: 80vh; /* 设置行高实现居中效果 line-height == 父容器height */
font-family: '楷体';
}
p {
color: #eee;
font-size: 16px;
line-height: 28px;
font-family: '宋体';
}
代码灵感来源出处参考于某站UP主@哆啦niko
demo源码
https://pan.baidu.com/s/1pUBvtIhQ8OYUW4QV_yJERQ?pwd=b1h6