CSS3 提供了许多创建动态效果的工具,例如变换(transforms)、动画(animations)、和过渡(transitions)。以下是一些常见的动态效果的实现方法:
- 图片轮播效果:
HTML:
<div class="slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
CSS:
.slider {
animation: slide 10s infinite;
}
.slider img {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
opacity: 0;
}
.slider img:first-child {
opacity: 1;
display: block;
}
@keyframes slide {
0% {
transform: translateX(0);
}
20% {
transform: translateX(-100%);
}
40% {
transform: translateX(-200%);
}
60% {
transform: translateX(-300%);
}
80% {
transform: translateX(-400%);
}
100% {
transform: translateX(-500%);
}
}
- 鼠标悬停时的动画效果:
HTML:
<button class="hover-effect">Hover Over Me!</button>
CSS:
.hover-effect {
background-color: #4CAF50;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
transition: background-color 0.5s;
}
.hover-effect:hover {
background-color: #008CBA;
}
- 加载时的进度条动画效果:
HTML:
<div class="loading-bar">
<div class="loading"></div>
</div>
CSS:
.loading-bar {
width: 100%;
background-color: #ddd;
position: relative;
height: 5px;
}
.loading {
width: 0%;
height: 100%;
background-color: #4CAF50;
animation: loading-bar 2s infinite;
text-align: center;
line-height: 5px; /* Center the text vertically */
color: white;
}
@keyframes loading-bar {
0% {
width: 0%;
}
100% {
width: 100%;
}
}
这些例子展示了如何使用 CSS3 的关键帧动画(@keyframes)和过渡(transitions)来创建动态效果。这些基本技术可以应用于创建各种动态交互,从简单的按钮悬停效果到复杂的页面内容切换。