一 原理
Parallax / 视差 的实现原理其实很简单,只是利用了物体的不同深度(depth)而已。因为背景中的物体比前景中的移动的更慢。
我们用transform-style: preserve-3d;
定义当前透视方法为3D。非常容易理解:
- 近大远小
- 近快远慢
![](https://img.haomeiwen.com/i2662224/90b4b01e5b060673.jpeg)
二 实现
当我们:
- 将透视锁定在鼠标滚动的"图层"(一般用
body
)transform-style: preserve-3d;
- 并在子元素上都标记
transform-style: preserve-3d;
时 - 为子元素标上
translateZ(0px / -5px / 5px)
===> 控制深度 - 将所有对象都伪装成在同一平面上:我们上面说过,因为每个对象都不在同一个深度上,对象的大小会因为深度不同而被缩放 ===> 可以用CSS的
scale()
来控制对象在屏幕上显示的大小
===> 注意,该属性不影响parallax scrolling的效果。只控制对象显示的大小(即缩放) - 为了保证某些元素被看见,我们可以使用
z-index
来改变堆叠顺序
然后,我们就可以看到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;
}
网友评论