CSS 中的过渡、动画和变换详解
一、CSS 过渡(Transitions)
1. 基本概念
CSS 过渡是一种平滑改变 CSS 属性值的机制,允许属性值在一定时间内从一个值逐渐变化到另一个值,从而创建流畅的动画效果。过渡只能用于具有中间值的属性(如颜色、大小、位置等),不能用于 display 等离散属性。
2. 核心属性
transition-property
指定哪些 CSS 属性参与过渡。可以是单个属性(如width
)、多个属性(如width, height
)或all
(所有可过渡属性)。
.element {transition-property: width, height;
}
transition-duration
指定过渡持续的时间,单位可以是秒(s)或毫秒(ms)。
.element {transition-duration: 0.5s; /* 0.5秒 */
}
transition-timing-function
定义过渡的速度曲线,常见值包括:
ease
:默认值,慢-快-慢linear
:匀速ease-in
:慢速开始ease-out
:慢速结束ease-in-out
:慢速开始和结束cubic-bezier(n,n,n,n)
:自定义贝塞尔曲线
.element {transition-timing-function: ease-in-out;
}
transition-delay
指定过渡开始前的延迟时间。
.element {transition-delay: 0.2s; /* 延迟0.2秒 */
}
3. 简写语法
.element {transition: width 0.5s ease-in-out 0.2s;/* 依次为:属性 持续时间 时间函数 延迟时间 */
}
4. 触发方式
过渡需要一个触发条件才能生效,常见的触发方式有:
:hover 伪类
.button {background-color: blue;transition: background-color 0.3s;
}.button:hover {background-color: red;
}
:focus 伪类
.input {border: 1px solid #ccc;transition: border-color 0.3s;
}.input:focus {border-color: blue;
}
JavaScript 动态修改
<button id="changeColor">变色</button>
<div id="box" style="width: 100px; height: 100px; background-color: red; transition: background-color 0.5s;"></div><script