利用background-attachment: fixed; 配合js设置background-position来实现。
具体的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body,
html {
margin: 0;
width: 100%;
height: 100%;
}
#bg1 {
width: 100%;
height: 100%;
background-color: antiquewhite;
background-image: url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594814547574&di=89f3c69ea703d15beb12d52c3dc07388&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fwallpaper%2F1304%2F17%2Fc5%2F19955421_1366189671581.jpg);
background-repeat: no-repeat;
background-size: 100% 100%;
background-attachment: fixed;
}
#bg2 {
width: 100%;
height: 100%;
background-color: antiquewhite;
background-image: url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594814547573&di=70f7d70fcf76e8032761f32425b64735&imgtype=0&src=http%3A%2F%2Fimg.pconline.com.cn%2Fimages%2Fupload%2Fupc%2Ftx%2Fwallpaper%2F1308%2F15%2Fc5%2F24496183_1376533418348.jpg);
background-size: 100% 120%;
background-repeat: no-repeat;
background-attachment: fixed;
}
#bg3 {
width: 100%;
height: 100%;
background-color: antiquewhite;
background-image: url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594814547573&di=c5ea816e268c2a5e857dc395b4c23b05&imgtype=0&src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201401%2F23%2F095609lsejfi4thjrrwydj.jpg);
background-size: 100% 140%;
background-repeat: no-repeat;
background-attachment: fixed;
}
</style>
</head>
<body>
<div id="bg1"></div>
<div id="bg2"></div>
<div id="bg3"></div>
<script>
const bg1 = document.querySelector('#bg1');
const bg2 = document.querySelector('#bg2');
const bg3 = document.querySelector('#bg3');
window.addEventListener("scroll", function () {
const t = document.documentElement.scrollTop / 10;
bg1.style.backgroundPositionY = -t + 'px';
bg1.style.transform = "translateY(" + (-t) + "px)";
bg2.style.backgroundPositionY = -t + 'px';
bg2.style.transform = "translateY(" + (-t) + "px)";
bg3.style.backgroundPositionY = -t + 'px';
bg3.style.transform = "translateY(" + (-t) + "px)";
});
</script>
</body>
</html>