一 原理
Parallax / 視差 的實(shí)現(xiàn)原理其實(shí)很簡(jiǎn)單,只是利用了物體的不同深度(depth)而已。因?yàn)楸尘爸械奈矬w比前景中的移動(dòng)的更慢。
我們用transform-style: preserve-3d;定義當(dāng)前透視方法為3D。非常容易理解:
????- 近大遠(yuǎn)小
????- 近快遠(yuǎn)慢

透視圖
二 實(shí)現(xiàn)
當(dāng)我們:
- 將透視鎖定在鼠標(biāo)滾動(dòng)的"圖層"(一般用
body)transform-style: preserve-3d; - 并在子元素上都標(biāo)記
transform-style: preserve-3d;時(shí) - 為子元素標(biāo)上
translateZ(0px / -5px / 5px)===> 控制深度 - 將所有對(duì)象都偽裝成在同一平面上:我們上面說(shuō)過(guò),因?yàn)槊總€(gè)對(duì)象都不在同一個(gè)深度上,對(duì)象的大小會(huì)因?yàn)樯疃炔煌豢s放 ===> 可以用CSS的
scale()來(lái)控制對(duì)象在屏幕上顯示的大小
===> 注意,該屬性不影響parallax scrolling的效果。只控制對(duì)象顯示的大小(即縮放) - 為了保證某些元素被看見(jiàn),我們可以使用
z-index來(lái)改變堆疊順序
然后,我們就可以看到Parallax的效果 ??? >>>?????YEAHHH
三 舉例
HTML
<div class="container">
<img class="main_pic" src="http://myfavoritewar.com/style/img/chars/ilze-02/ilze-02-03.png" />
<img class="pic1 pic" src="https://cdn.pixilart.com/images/user/profile/small/fac436637a24e88.png?v=1521437170"></img>
<img class="pic2 pic" src="http://www.nearbynerd.com.au/files/imagecache/thumbnailer/profile_pics/WebPhoenix/banner4.png"></img>
<img class="pic3 pic" src="https://www.eurobricks.com/forum/uploads/monthly_2017_06/594e29afc0703_logoWEByellow.thumb.png.563f4d5930f282d6a5eece7bdadf5579.png"></img>
<img class="pic4 pic" src="https://da57fee7585ze.cloudfront.net/assets/original/competition/default_thumb.png"></img>
<img class="pic5 pic" src="http://0.gravatar.com/avatar/61cd3d5f7adf14b70c3e881bad548175?s=50&d=identicon&r=pg"></img>
</div>
CSS
html, body {
width: 100%; height: 100%;
margin: 0; padding: 0;
overflow: hidden;
}
body {
overflow: auto;
perspective: 1px;
-webkit-perspective: 1px;
transform-style: preserve-3d;
-webkit-transform-style: preserve-3d;
}
body * {
transform-style: preserve-3d;
-webkit-transform-style: preserve-3d;
}
.container {
height: 1280px;
position: relative;
}
.main_pic {
height: 800px; left: 50%;
position: absolute;
-webkit-transform: translate3D(-50%, -120px, -1px) scale(2);
transform: translate3D(-50%, -120px, -1px) scale(2);
z-index: 1000;
}
.pic {
position: absolute;
}
.pic1 {
top: 200px; left: 200px;
-webkit-transform: translateZ(-0.4px) scale(2);
transform: translateZ(-0.4px) scale(2);
z-index: -1;
}
.pic2 {
top: 400px; left: 1000px;
-webkit-transform: translateZ(-0.4px) scale(3);
transform: translateZ(-0.4px) scale(3);
z-index: 0;
}
.pic3 {
top: 500px; left: 100px;
-webkit-transform: translateX(-0.4px) scale(1);
transform: translateX(-0.4px) scale(1);
z-index: 1;
}
.pic4 {
top: 800px; left: 900px;
-webkit-transform: translateX(2px) scale(2);
transform: translateX(2px) scale(2);
z-index: 1;
}
.pic5 {
top: 900px; left: 400px;
-webkit-transform: translateX(-1px) scale(2);
transform: translateX(-1px) scale(2);
z-index: 1;
}