过渡

Frontend SELF ZH
第 23 级 , 课程 3
可用

4.1 transition属性

CSS过渡(transition)可以对CSS属性值的变化进行动画处理,从而在其初始和最终状态之间创建平滑的过渡。这是一个强大的工具,可以通过为网页添加活力来提高用户体验。我们来看看过渡的主要方面,包括属性、持续时间和时间函数。

属性 transition 将过渡的所有方面组合成一个属性。它可以包括:

  1. 要动画化的属性。
  2. 动画持续时间。
  3. 时间函数。
  4. 动画开始前的延迟(可选)。

语法:

    
      element {
        transition: property duration timing-function delay;
      }
    
  

其中:

  • property: 应用过渡的属性(例如,widthheightbackground-color
  • duration: 过渡的持续时间(例如,2s 为2秒或 500ms 为500毫秒)
  • timing-function: 定义动画速度变化的时间函数(例如, easelinearease-inease-outease-in-out
  • delay: 过渡开始前的延迟(例如,1s 表示一秒)

示例:

HTML
    
      
       
   
内容
CSS
    
      .box {
        width: 100px;
        height: 100px;
        background-color: #3498db;
        transition: width 2s ease-in-out, background-color 1s ease;
      }
    
  

代码解释:

  • transition: width 2s ease-in-out, background-color 1s ease: 定义了两个过渡:一个是 width 属性的过渡,持续时间为2秒,时间函数为 ease-in-out,另一个是 background-color 属性的过渡,持续时间为1秒,时间函数为 ease

4.2 过渡属性

1. transition-property 属性

属性 transition-property 定义了哪些元素属性将应用过渡效果。

语法:

    
      element {
        transition-property: property1, property2 ...;
      }
    
  

示例:

CSS
    
      .box {
        transition-property: width, height, background-color;
      }
    
  

2. transition-duration 属性

属性 transition-duration 设置过渡的持续时间。

语法:

    
      element {
        transition-duration: time;
      }
    
  

示例:

CSS
    
      .box {
        transition-duration: 2s, 1s, 3s;
      }
    
  

3. transition-timing-function 属性

属性 transition-timing-function 定义动画在时间内的速度变化。

语法:

    
      element {
        transition-timing-function: function;
      }
    
  

示例:

CSS
    
      .box {
        transition-timing-function: ease-in, linear, ease-out;
      }
    
  

4. transition-delay 属性

属性 transition-delay 设置过渡开始前的延迟时间。

语法:

    
      element {
        transition-delay: time;
      }
    
  

示例:

CSS
    
      .box {
        transition-delay: 1s, 0s, 500ms;
      }
    
  

4.3 过渡的持续时间

过渡持续时间决定了一个属性变化的动画将持续多长时间。它以秒(s)或毫秒(ms)为单位指定。

示例:

CSS
    
      .box {
        width: 100px;
        height: 100px;
        background-color: #3498db;
        transition: width 2s, height 1s, background-color 500ms;
      }
    
  

代码解释:

  • transition: width 2s, height 1s, background-color 500ms: 定义了 width 属性的过渡持续2秒,height 属性持续1秒,以及 background-color 属性持续500毫秒。

4.4 时间函数

时间函数定义了属性值在时间内如何变化。它们允许创建各种动画效果。

主要时间函数:

  • ease: 动画开始很慢,中间加速,结束时减速
  • linear: 动画从开始到结束以恒定速度发生
  • ease-in: 动画开始缓慢,然后加速
  • ease-out: 动画开始快速,然后减速
  • ease-in-out: 动画开始和结束时缓慢,中间加速

示例:

CSS
    
      .box {
        width: 100px;
        height: 100px;
        background-color: #2ecc71;
        transition: width 2s ease-in-out, height 1s linear, background-color 500ms ease;
      }
    
  

代码解释:

  • ease-in-out: 平滑的过渡,开始和结束都很慢
  • linear: 恒定速度的过渡
  • ease: 中间加速,开始和结束慢慢的过渡
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION