過渡

Frontend SELF TW
等級 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表示1秒)

範例:

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