CSS3 过渡学习笔记
CSS3 过渡(transition)是一种可以让元素在发生改变时产生平滑过渡效果的技术,可用于添加动画效果或增强用户体验。在本篇笔记中,我们将学习如何使用 CSS3 过渡实现不同的动画效果,并举例说明。
基本语法
要使用过渡,需要为元素指定一个过渡的属性(transition-property)、持续时间(transition-duration)、过渡效果的速度曲线(transition-timing-function)和延迟时间(transition-delay)。
cssCopy Code/* 用 transition 属性实现一个过渡 */
.box {
width: 100px;
height: 100px;
background-color: red;
transition: width 2s;
}
/* 鼠标悬停时触发过渡 */
.box:hover {
width: 200px;
}
上面的代码演示了如何将 .box
元素的宽度属性从 100px
过渡到 200px
,并在鼠标悬停时触发过渡。过渡的持续时间设置为 2s
,默认的过渡效果速度曲线是 ease
,延迟时间默认为 0s
。
过渡的属性
可以通过设置 transition-property
属性来指定要过渡的 CSS 属性。如果想要所有属性都过渡,可以使用关键字 all
。
cssCopy Code.box {
transition-property: width, height, background-color;
}
.box {
transition-property: all;
}
过渡的持续时间
可以通过设置 transition-duration
属性来指定过渡的持续时间,单位为秒(s)或毫秒(ms)。
cssCopy Code.box {
transition-duration: 2s;
}
过渡效果的速度曲线
可以通过设置 transition-timing-function
属性来指定过渡效果的速度曲线,默认值是 ease
。常见的速度曲线有:linear
(线性)、ease-out
(减速)、ease-in
(加速)、ease-in-out
(先加速再减速)等。
cssCopy Code.box {
transition-timing-function: ease-out;
}
过渡的延迟时间
可以通过设置 transition-delay
属性来指定过渡的延迟时间,单位为秒(s)或毫秒(ms)。
cssCopy Code.box {
transition-delay: 1s;
}
举例说明
下面是一些使用 CSS3 过渡实现的动画效果。
点击按钮改变背景色
htmlCopy Code<button id="btn">点击我</button>
<div class="box"></div>
cssCopy Code/* 初始状态 */
.box {
width: 100px;
height: 100px;
background-color: red;
}
/* 当按钮被点击时,改变背景色 */
#btn {
margin-top: 20px;
padding: 10px;
background-color: #333;
color: #fff;
border: none;
outline: none;
cursor: pointer;
}
#btn:hover {
background-color: #555;
}
#btn.clicked + .box {
background-color: blue;
transition: background-color 1s;
}
javascriptCopy Code// 点击按钮时添加 clicked 类名
document.getElementById("btn").addEventListener("click", function() {
this.classList.add("clicked");
});
图片旋转动画
htmlCopy Code<div class="box">
<img src="image.jpg" alt="图片">
</div>
cssCopy Code/* 初始状态 */
.box {
width: 200px;
height: 200px;
overflow: hidden;
}
/* 鼠标悬停时,图片逆时针旋转 360 度 */
.box img {
width: 100%;
height: auto;
transition: transform 2s ease-in-out;
}
.box:hover img {
transform: rotate(-360deg);
}
这些例子只是 CSS3 过渡的冰山一角。欢迎继续探索和尝试,发现更多的动画效果!