偶然看到了QQ官网的设计,感觉这种视差滚动很有趣,就仿了一个。
主要是为图片背景设置background-attachment: fixed;
使其定在页面上,然后通过JS控制background-position-y
来产生轻微位移,就可以达到QQ官网那种效果了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>I'm QQ</title>
<style>
body {
padding: 0;
margin: 0;
}
#header {
height: 50px;
background-color: dodgerblue;
}
#pics {
height: 500px;
background-color: cadetblue;
}
.sections {
background-color: #fff;
height: 300px;
text-align: center;
font-size: 30px;
padding: 50px;
}
.section-bgs {
height: 600px;
background-repeat: no-repeat;
background-position-x: 50%;
background-attachment: fixed;
}
#section-1-bg {
background-image: url(https://sqimg.qq.com/qq_product_operations/im/2015/bg1_1600.jpg);
}
#section-2-bg {
background-image: url(https://sqimg.qq.com/qq_product_operations/im/2015/update/avds.jpg);
}
#section-3-bg {
background-image: url(https://sqimg.qq.com/qq_product_operations/im/2015/bg3_1600.jpg);
}
</style>
</head>
<body>
<div id="header"></div>
<div id="pics"></div>
<div id="pages">
<div id="section-1" class="sections">
每一天,乐在沟通
</div>
<div id="section-1-bg" class="section-bgs"></div>
<div id="section-2" class="sections">
沟通,是随时随地爽快收发
</div>
<div id="section-2-bg" class="section-bgs"></div>
<div id="section-3" class="sections">
沟通,是跨越千山万水的亲切声音
</div>
<div id="section-3-bg" class="section-bgs"></div>
</div>
<script>
function getTop(node) {
return node.getBoundingClientRect().top;//获取元素的绝对位置
}
function setBgPosY(node, posY) {
node.style.backgroundPositionY = `${posY}px`;
}
const sections = document.querySelectorAll('.section-bgs');
window.onscroll = (e) => {
sections.forEach((node) => {
setBgPosY(node, getTop(node) / 20);
});
}
</script>
</body>
</html>