看到别的网站有这样一个效果觉得很有意思,有点像公众号里面的svg效果,就尝试用代码实现了一下。实现思路大致如下。
顺便给大家分享一个有意思的插件,有兴趣的朋友可以研究一下怎么利用这个插件实现:
Parallax scrolling with CSS variables | basicScroll
html部分:
- 固定一个容器用来装三张图片(相对定位);
- 给容器设置一张默认背景图片;
- 容器内新增两个块级容器用来存放另外两张图片,
- 容器内两个块级容器设置z-index用来层级展示(绝对定位);
js部分:
- 获取容器内的两张图片dom元素;
- 监听当前浏览器的滚动事件;
- 根据滚动距离与图片位置进行动态计算;
<!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>template</title>
<style>
body {
height: 300vh;
background-color: black;
}
.behind {
height: 100vh;
}
.container {
width: 100%;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.box {
width: 120px;
height: 208px;
background: url(./image/3.png) no-repeat center center;
background-size: 100% 100%;
margin: 0 auto;
position: relative;
overflow: hidden;
}
.box1 {
position: absolute;
top: 0;
left: 0;
width: 120px;
height: 208px;
background: url(./image/2.png) no-repeat center center;
background-size: 100% 100%;
z-index: 1;
}
.box2 {
position: absolute;
top: 0;
left: 0;
width: 120px;
height: 208px;
background: url(./image/1.png) no-repeat center center;
background-size: 100% 100%;
z-index: 2;
}
</style>
</head>
<body>
<div class="behind"></div>
<div class="container">
<div class="box">
<div class="box1"></div>
<div class="box2"></div>
</div>
</div>
</body>
<script>
// 定义两张图片的滚动位置
let top1 = 520;
let top2 = 660;
// 获取图片的DOM元素
const box1 = document.querySelector('.box1')
const box2 = document.querySelector('.box2')
// 监听浏览器的滚动
document.addEventListener('scroll', function() {
const scrollTop = document.documentElement.scrollTop
// 如果当前滚动位置大于第一张图片的位置,则进行样式赋值, top * 3为滚动大小幅度
if (scrollTop > top1) {
const top = (scrollTop - top1) / 2
if (top < 0) top = 0
box2.style.top = `-${top * 3}px`
}
// 大于第二章图片的位置,则同上操作
if (scrollTop > top2) {
const top = (scrollTop - top2) / 2
if (top < 0) top = 0
box1.style.top = `-${top * 3}px`
}
})
</script>
</html>