CSS3 过渡(transition)是一种在元素的属性值发生变化时,让这些变化以一种平滑的动画效果展示出来的技术。通过过渡,我们可以实现在鼠标悬停时元素颜色渐变、大小缩放等效果,让页面更加生动和吸引人。
语法
过渡的语法非常简单,只需要在元素的样式中添加 transition 属性即可。其基本语法如下:
.element {
transition: property duration timing-function delay;
}property:指定要过渡的 CSS 属性名称,可以是all表示所有属性。duration:指定过渡效果持续的时间,单位为秒(s)或毫秒(ms)。timing-function:指定过渡效果的时间函数,常用的有ease(默认值)、linear、ease-in、ease-out等。delay:指定过渡效果延迟的时间,单位为秒(s)或毫秒(ms)。
示例
下面是一个简单的示例,当鼠标悬停在按钮上时,按钮的背景颜色将发生渐变效果:
// www.javascriptcn.com code example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS3 Transition Example</title>
<style>
.button {
padding: 10px 20px;
background-color: #3498db;
color: #fff;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<button class="button">Hover me</button>
</body>
</html>在上面的示例中,当鼠标悬停在按钮上时,按钮的背景颜色将在 0.3 秒内以 ease 时间函数的方式发生渐变效果。
通过使用 CSS3 过渡,我们可以轻松实现各种动画效果,为网页增添更多交互性和视觉吸引力。