PHP前端开发

CSS 过渡和动画

百变鹏仔 4周前 (09-19) #CSS
文章标签 动画

第 7 讲:css 过渡和动画

在本次讲座中,我们将探索如何使用 css 过渡和动画让您的网页栩栩如生。这些技术允许您创建流畅、引人入胜的效果,从而增强用户体验,而无需 javascript。


css 过渡简介

css 转换使您能够在指定的持续时间内平滑地更改属性值。它们非常适合创建悬停效果、按钮动画和其他交互元素。

1.基本语法

要创建过渡,您需要指定要过渡的 css 属性、持续时间和可选的缓动函数。

  .button {    background-color: #4caf50;    transition: background-color 0.3s ease;  }  .button:hover {    background-color: #45a049;  }

在此示例中,悬停时按钮的背景颜色会在 0.3 秒内平滑变化。

立即学习“前端免费学习笔记(深入)”;

2.转换多个属性

您可以通过用逗号分隔多个属性来一次转换它们。

  .box {    width: 100px;    height: 100px;    background-color: #333;    transition: width 0.5s, height 0.5s, background-color 0.5s;  }  .box:hover {    width: 150px;    height: 150px;    background-color: #555;  }

此示例在悬停时平滑地更改框的宽度、高度和背景颜色。

3.缓动函数

缓动函数控制不同点的过渡速度,创建缓入、缓出或两者兼而有之的效果。

css 动画简介

css 动画允许您随着时间的推移创建更复杂的变化序列,而不仅仅是简单的过渡。您可以为多个属性设置动画、控制时间并创建关键帧以实现更好的控制。

1.基本语法

要创建动画,请定义关键帧并使用动画属性将它们应用到元素。

  @keyframes example {    0% {background-color: red; left: 0px;}    50% {background-color: yellow; left: 100px;}    100% {background-color: green; left: 0px;}  }  .animate-box {    position: relative;    width: 100px;    height: 100px;    background-color: red;    animation: example 5s infinite;  }

在此示例中:

2.控制动画时间

您可以控制动画的时间、延迟和迭代次数。

  .animate-box {    animation: example 5s ease-in-out 1s 3 alternate;  }
3.结合过渡和动画

您可以结合使用转场和动画来创建更多动态效果。

  .button {    background-color: #4caf50;    transition: transform 0.3s ease;  }  .button:hover {    transform: scale(1.1);  }  @keyframes pulse {    0% {transform: scale(1);}    50% {transform: scale(1.2);}    100% {transform: scale(1);}  }  .pulse-button {    animation: pulse 1s infinite;  }

这个例子:

实际示例:

让我们结合过渡和动画来创建一个响应式、交互式按钮。

html:

<button class="animated-button">hover me!</button>

css:

.animated-button {  padding: 15px 30px;  font-size: 16px;  color: white;  background-color: #008CBA;  border: none;  border-radius: 5px;  cursor: pointer;  transition: background-color 0.3s ease, transform 0.3s ease;}.animated-button:hover {  background-color: #005f73;  transform: translateY(-5px);}@keyframes shake {  0% { transform: translateX(0); }  25% { transform: translateX(-5px); }  50% { transform: translateX(5px); }  75% { transform: translateX(-5px); }  100% { transform: translateX(0); }}.animated-button:active {  animation: shake 0.5s;}

在此示例中:

练习运动

  1. 为链接创建悬停效果,更改其颜色并使用过渡添加下划线。
  2. 创建一个以圆圈方式移动元素的关键帧动画。
  3. 结合过渡和动画来创建交互式元素,例如可以在交互时缩放、更改颜色或动画的按钮或卡片。

下一步:在下一堂课中,我们将探索 css flexbox 深入探究,您将学习如何充分利用 flexbox 来创建高级的响应式布局。请继续关注!


在 linkedin 上关注我

里多伊·哈桑