css之3D变换
一.3D变换示例代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>3D变换</title> 6 <style type="text/css"> 7 #box{ 8 width: 100px; 9 height: 100px; 10 padding: 100px; 11 border: 5px solid blue; 12 border-radius: 10px; 13 margin: 100px auto; 14 /*span的父级div搭建3d环境*/ 15 transform-style: preserve-3d; 16 /*添加景深,景深就是:彼此相隔多少距离的视角*/ 17 perspective:300px; 18 } 19 span{ 20 display: block; 21 width: 100px; 22 height: 100px; 23 background: purple; 24 transition: 1s; 25 } 26 #box:hover span{ 27 transform: translateZ(200px); 28 } 29 </style> 30 </head> 31 <body> 32 <!-- 33 3d效果,首先需要给需要进行3d变换的元素的父级,添加3d环境和景深 34 方法: 35 transform-style:preserve-3d;添加3d环境 36 perspective:数值;如:300px; 37 38 相应的变化: 39 transform: 40 增加了rotateZ; 41 增加了translateZ; 42 兼容:IE9以下不支持 43 --> 44 <div id="box"> 45 <span></span> 46 </div> 47 </body> 48 </html>
二.3D变换小例子(转骰子)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>3D变换小例子</title> 6 <style type="text/css"> 7 #box{ 8 width: 100px; 9 height: 100px; 10 padding: 100px; 11 border: 4px solid red; 12 margin: 100px auto; 13 perspective: 300px; 14 } 15 #val{ 16 width: 100px; 17 height: 100px; 18 position: relative; 19 transition: 1s; 20 transform-origin: center center -50px; 21 /*需要变换的是span故3d环境建立在其父级上*/ 22 transform-style: preserve-3d; 23 } 24 #val div{ 25 position: absolute; 26 width: 100px; 27 height: 100px; 28 background: red; 29 text-align: center; 30 font:40px/100px "simhei"; 31 } 32 #val div:nth-of-type(1){ 33 top: -100px; 34 background: purple; 35 transform-origin: bottom; 36 transform: rotateX(90deg); 37 } 38 #val div:nth-of-type(2){ 39 left: -100px; 40 background: blue; 41 transform-origin: right; 42 transform: rotateY(-90deg); 43 } 44 #val div:nth-of-type(3){ 45 background: #96EF24; 46 } 47 #val div:nth-of-type(4){ 48 left: 100px; 49 background: pink; 50 transform-origin: left; 51 transform: rotateY(90deg); 52 } 53 #val div:nth-of-type(5){ 54 top: 100px; 55 background: #3D006D; 56 transform-origin: top; 57 transform: rotateX(-90deg); 58 } 59 #val div:nth-of-type(6){ 60 background: gray; 61 transform: translateZ(-100px) rotateX(-180deg); 62 /*在鼠标经过旋转前将6调整角度,以便鼠标经过旋转后看见正常的6*/ 63 } 64 #box:hover #val{ 65 /*此时是按照3这面的x轴旋转了180度,故6倒转看见的是9*/ 66 transform: rotateX(180deg) rotateY(300deg); 67 } 68 </style> 69 </head> 70 <body> 71 <div id="box"> 72 <div id="val"> 73 <div>1</div> 74 <div>2</div> 75 <div>3</div> 76 <div>4</div> 77 <div>5</div> 78 <div>6</div> 79 </div> 80 </div> 81 82 83 </body> 84 </html>
温馨小提示:重要的是理解了x、y、z轴是哪条线,旋转的正值是顺时针、负值是逆时针(不对请允于指正,感激)