css3实现图片旋转木马效果
代码如下
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title><style>body{perspective: 1000px;}section{position: relative;width: 300px;height: 200px;margin: 150px auto;transform-style: preserve-3d;/* 添加动画 */animation: rotate 10s linear infinite; }@keyframes rotate{0%{transform:rotateY(0);}100%{transform:rotateY(360deg);}}section div{position: absolute;top: 0;left: 0;width: 100%;height: 100%;background: url(../images/s6.jpeg) no-repeat;background-size: contain;}section div:nth-child(1){transform: translateZ(300px);}section div:nth-child(2){/* 先旋转 再移动 */transform: rotateY(60deg) translateZ(300px);}section div:nth-child(3){transform: rotateY(120deg) translateZ(300px);}section div:nth-child(4){transform: rotateY(180deg) translateZ(300px);}section div:nth-child(5){transform: rotateY(240deg) translateZ(300px);}section div:nth-child(6){transform: rotateY(300deg) translateZ(300px);}</style></head><body><section><div></div><div></div><div></div><div></div><div></div><div></div></section><script></script></body></html>
大盒子里面有六个小盒子(60*6 每个60度刚好)
小盒子用绝对定位,定位到一起,子绝父相。
第一个盒子不用旋转,往z轴前面移动300px。
第二个盒子旋转60度,旋转之后,轴会发生变化,此时图片正面所对就是z轴正方向,在往z轴移动300px。(此处一定是先旋转后移动)
transform: rotateY(60deg) translateZ(300px);
第三个盒子旋转120度,旋转之后也是向前移动300px
…
依次类推
每一个盒子旋转相应的度数,往前移动相同的距离,就像是从中心点发散一样。
最后给父盒子加上动画效果
@keyframes rotate{0%{transform:rotateY(0);}100%{transform:rotateY(360deg);}}
此处360deg为正,则顺时针移动,为负,则逆时针移动。