首先给出 <body> 和 <style> 中的基础代码
<body>
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
<style>
.box1 {
width: 500px;
height: 500px;
background-color: yellowgreen;
}
.box1 div {
width: 100px;
height: 50px;
}
.box2 {
background-color: aqua;
margin-bottom: 100px;
}
.box3 {
background-color: antiquewhite;
}
.box1:hover div {
}
基础代码实现的效果如下图:
(接下来将使用 box1 与 box2 作对比,容易看出区别)
接下来讲解一下 transition 的属性:
1、transition-property 用于指定要执行过渡的属性
- 多个属性之间使用 ',' 隔开
- 如果所有属性都需要过渡,则使用 all 关键字
- 大部分属性都支持过渡效果,注意过渡时必须是从一个有效数值向另外一个有效数值进行过渡
2、transition-duration 用于指定过渡效果的持续时间
- 时间单位: s 秒 和 ms 毫秒
以上两个属性必须同时给定,否则是不会出现过渡效果的,下面给出例子:
我们修改 CSS 代码,将 .box2 与 .box1:hover div 的代码改为:
.box2 {
background-color: aqua;
margin-bottom: 100px;
transition-property: width, height;
transition-duration: 2s, 1000ms;
}
.box1:hover div {
width: 200px;
height: 100px;
}
修改之后的效果为:
(width 对应 2s ,height 对应 1000ms)
3、transition-timing-function 表示过渡的时序函数
- 指定过渡的执行方式
- 可选值:
ease 默认值,慢速开始,先加速,再减速
linear 匀速运动
ease-in 加速运动
ease-out 减速运动
ease-in-out 先加速 后减速
cubic-bezier() 来制定时序函数(贝塞尔曲线)
- https://cubic-bezier.com ,这是一个贝塞尔曲线的网址,可以自己拖动曲线,
获取想要的结果,有兴趣的小伙伴可以试试
steps() 分步执行过渡效果
- 第一个参数表示分几步
- 第二个参数:
start 在时间开始时就执行过渡
end 在时间结束时执行过渡(默认值)
例子:
我们在最基础的代码上进行修改:
.box2 {
background-color: aqua;
margin-bottom: 100px;
transition-property: margin-left;
transition-duration: 2s;
}
.box3 {
background-color: antiquewhite;
transition-property: margin-left;
transition-duration: 2s;
transition-timing-function: linear;
}
.box1:hover div {
margin-left: 400px;
}
效果如下:
(其余的 ease-in , ease-out , ease-in-out , 就不分别演示了)
这是使用 cubic-bezier() 的例子,可以得到很好玩的效果:
(将 .box3 的 transition-timing-function 修改为为:)
.box3 {
transition-timing-function: cubic-bezier(.13,1.51,.82,-0.59);
}
效果如下:
steps() 则是分步进行,我们同样修改 .box3 的 transition-timing-function:
.box3 {
transition-timing-function: steps(3,start);
}
效果如下:
(start 与 end 的区别则是执行时间,假设过渡时间 transition-duration:10s ,分为两步执行 steps(2,end),则会在数完第一个五秒才开始移动,若为 steps(2,start),则在最开始就会开始移动)
4、transition-delay: 过渡效果的延迟,等待一段时间后再执行过渡
修改 CSS 代码:
.box3 {
background-color: antiquewhite;
transition-property: margin-left;
transition-duration: 2s;
transition-delay: 1s;
}
效果如下:
最后则是最常用的 transition :
transition 可以同时设置过渡相关的所有属性,只有一个要求,如果要写延迟,则两个时间中第一个是持续时间,第二个是延迟时间(前面说的一堆乱七八糟的属性都可以用这个属性来简写)
修改 CSS 代码:
.box3 {
background-color: antiquewhite;
/* transition-property: margin-left;
transition-duration: 2s;
transition-delay: 1s; */
transition: margin-left 2s 1s;
}
(效果与上一个例子相同,故略)
当然也可以同时指定多个属性,对应不同的时间,也可以添加时序函数:
.xxx{
transition: width,height 2s,1s 1s steps(2,end);
}