一、空间转换 3D
3D坐标系
3D 坐标系比2D 多了一个Z轴。
一定要记住3个坐标轴取值的正反:
- X 轴 向右是正值, 向左是负值
- Y 轴 向下是正值,向左是负值
- Z轴 指向我们是正值,否则反之
3D位移
有完整写法:
transform: translate3d(x, y, z);
只不过在很多情况下,我们经常喜欢分开写:
transform: translateX(100px);
transform: translateY(100px);
transform: translateZ(100px);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
/* 3d位移的写法 */
/* x y z之间用逗号隔开 */
/* transform: translate3d(x,y,z); */
transform: translate3d(100px, 100px, 200px);
transform: translate3d(100px, 0, 0);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
透视
透视的作用: 空间转换时,为元素添加近大远小、近实远虚的视觉效果
语法:
perspective: 800px;
透视注意事项:
-
取值范围经常在 800px ~ 1200px 之间。
-
给父元素添加
-
透视距离也称为视距,所谓的视距就是人的眼睛到屏幕的距离。
-
其中 d 为透视的距离
-
z 是
translateZ的距离, 这个距离靠近我们,盒子越大
-
3D旋转
有了透视的加持,我们3d旋转效果会比较明显。
rotateX
类似单杠旋转。
注意:默认的旋转中心在盒子的中心位置。
body {
/* 父级添加透视 */
perspective: 800px;
}
img {
transition: all 1s;
}
img:hover {
transform: rotateX(360deg);
}
效果展示:
rotateY
类似钢管舞旋转。
body {
perspective: 400px;
}
img {
transition: all 1s;
}
img:hover {
transform: rotateY(360deg);
}
效果如下:
左手法则
一定要搞清楚X轴和Y轴如何旋转的,旋转的度数是正值还是负值。
规则:
- 大拇指指向X轴正向方(右), 则四指指向的方向是旋转的正方向
- 大拇指指向Y轴正向方(下), 则四指指向的方向是旋转的正方向
立体呈现
让子盒子在父盒子内有空间的展示,此时可以给父亲添加transform-style属性。
transform-style: preserve-3d;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>立体呈现</title>
<style>
.cube {
position: relative;
width: 200px;
height: 200px;
margin: 100px auto;
transition: all .5s;
background-color: pink;
/* 3d呈现 */
transform-style: preserve-3d;
}
.cube div {
/* 1.1 添加定位 让2个盒子叠加在一起 */
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 200px;
}
.front {
/* 向我们面前拉(移动) */
background-color: orange;
/* transform: translateZ(200px); */
transform: translateZ(100px);
}
.back {
background-color: green;
transform: translateZ(-100px);
}
.cube:hover {
transform: rotateY(65deg);
}
</style>
</head>
<body>
<div class="cube">
<div class="front">前面</div>
<div class="back">后面</div>
</div>
</body>
</html>
二、动画(重点)
动画最大的特点可以不用鼠标触发,自动的,反复的执行某些动画。
动画使用分为定义和调用:
-
定义:
/* 1. 定义的动画 */ @keyframes dance { from { transform: scale(1) } to { transform: scale(1.5) } }或者是
/* 1. 定义的动画 */ @keyframes dance { 0% { transform: scale(1) } 100% { transform: scale(1.5) } } -
调用
img { width: 200px; /* 2. 使用动画 animation: 动画名称 执行时间; infinite 循环*/ animation: dance .5s infinite; }
动画属性
- 动画名字参照css类选择器命名
- 动画时长和延迟时间别忘了带单位 s
- infinate 无限循环动画
- alternate 为反向 就是左右来回执行动画(跑马灯)
- forwards 动画结束停留在最后一帧状态
- linear 让动画匀速执行
鼠标经过暂停动画
/* 鼠标经过box, 则 ul 停止动画 */
.box:hover ul {
animation-play-state: paused;
}
多组动画
/* 我们想要2个动画一起执行 animation: 动画1, 动画2, ... 动画n */
animation: run 1s steps(12) infinite, move 5s linear forwards;