填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

動畫轉場與觸發器

Animations transitions and triggers

你已經在簡介頁學習了 Angular 動畫的基礎知識。

You learned the basics of Angular animations in the introduction page.

本章將深入講解特殊的轉場狀態,如 *(萬用字元)和 void,並說明這些特殊狀態如何作用於進入或離開檢視的元素。本章還探討了多重觸發器、動畫回呼(Callback),以及使用關鍵幀技術的序列動畫。

This guide goes into greater depth on special transition states such as * (wildcard) and void, and show how these special states are used for elements entering and leaving a view. This chapter also explores multiple animation triggers, animation callbacks, and sequence-based animation using keyframes.

預定義狀態與萬用字元匹配

Predefined states and wildcard matching

在 Angular 中,轉場狀態可以透過 state() 函式進行顯式定義,或使用預定義的 *(萬用字元)狀態和 void 狀態。

In Angular, transition states can be defined explicitly through the state() function, or using the predefined * (wildcard) and void states.

萬用字元狀態

Wildcard state

星號 * 或者叫萬用字元可以匹配任何一個動畫狀態。它可用來定義那些不用在乎 HTML 元素的起始狀態或結束狀態的轉場動畫。

An asterisk * or wildcard matches any animation state. This is useful for defining transitions that apply regardless of the HTML element's start or end state.

比如,一個 open => * 轉場可應用在當元素的狀態從 open 變成任何其它狀態時。

For example, a transition of open => * applies when the element's state changes from open to anything else.

下面是萬用字元狀態的另一個程式碼範例,以及我們以前使用 openclosed 狀態的實例。但這次,對於每個狀態到狀態的轉換對,我們這次規定從任何狀態轉場到 closed 狀態時要花 1 秒鐘,而從任何狀態轉場到 open 狀態時要花 0.5 秒。

The following is another code sample using the wildcard state together with the previous example using the open and closed states. Instead of defining each state-to-state transition pair, any transition to closed takes 1 second, and any transition to open takes 0.5 seconds.

這讓我們可以新增新狀態,而不必把它手動包含到每個單獨的轉場中。

This allows us to add new states without having to include separate transitions for each one.

src/app/open-close.component.ts
      
      animations: [
  trigger('openClose', [
    // ...
    state('open', style({
      height: '200px',
      opacity: 1,
      backgroundColor: 'yellow'
    })),
    state('closed', style({
      height: '100px',
      opacity: 0.5,
      backgroundColor: 'green'
    })),
    transition('* => closed', [
      animate('1s')
    ]),
    transition('* => open', [
      animate('0.5s')
    ]),
  ]),
],
    

使用雙向箭頭語法可以指定任意方向的狀態轉場。

Use a double arrow syntax to specify state-to-state transitions in both directions.

src/app/open-close.component.ts
      
      transition('open <=> closed', [
  animate('0.5s')
]),
    

使用帶多個轉場狀態的萬用字元狀態

Using wildcard state with multiple transition states

在這個雙態按鈕的例子中,萬用字元不是很有用,因為只有兩種可能的狀態:openclosed。當一個特定狀態下的元素可能變更為多個潛在狀態時,萬用字元狀態會更好用。如果我們的按鈕可以從 open 變成 closed 或類似 inProgress 的狀態,則可以使用萬用字元狀態來減少所需的編碼量。

In the two-state button example, the wildcard isn't that useful because there are only two possible states, open and closed. Wildcard states are better when an element in one particular state has multiple potential states that it can change to. If the button can change from open to either closed or something like inProgress, using a wildcard state could reduce the amount of coding needed.

src/app/open-close.component.ts
      
      animations: [
  trigger('openClose', [
    // ...
    state('open', style({
      height: '200px',
      opacity: 1,
      backgroundColor: 'yellow'
    })),
    state('closed', style({
      height: '100px',
      opacity: 0.5,
      backgroundColor: 'green'
    })),
    transition('open => closed', [
      animate('1s')
    ]),
    transition('closed => open', [
      animate('0.5s')
    ]),
    transition('* => closed', [
      animate('1s')
    ]),
    transition('* => open', [
      animate('0.5s')
    ]),
    transition('open <=> closed', [
      animate('0.5s')
    ]),
    transition ('* => open', [
      animate ('1s',
        style ({ opacity: '*' }),
      ),
    ]),
    transition('* => *', [
      animate('1s')
    ]),
    

當在任意兩個狀態之間切換時,* => * 轉場都會生效。

The * => * transition applies when any change between two states takes place.

轉場會按照其定義的順序進行匹配。因此,你可以在 * => * 轉場的前面定義其它轉場。比如,定義只針對 open => closed 的狀態變更或動畫,或 closed => open,而使用 * => * 作為匹配不上其它狀態對時的後備。

Transitions are matched in the order in which they are defined. Thus, you can apply other transitions on top of the * => * (any-to-any) transition. For example, define style changes or animations that would apply just to open => closed, or just to closed => open, and then use * => * as a fallback for state pairings that aren't otherwise called out.

要這麼做,只要把那些更特殊的轉場放在 * => * 前面就行了。

To do this, list the more specific transitions before * => *.

使用帶樣式的萬用字元狀態

Using wildcards with styles

使用帶樣式的 * 萬用字元來告訴動畫使用當前的狀態值,並用它進行動畫處理。萬用字元是一個後備值,如果未在觸發器中宣告動畫狀態,就會使用這個值。

Use the wildcard * with a style to tell the animation to use whatever the current style value is, and animate with that. Wildcard is a fallback value that's used if the state being animated isn't declared within the trigger.

src/app/open-close.component.ts
      
      transition ('* => open', [
  animate ('1s',
    style ({ opacity: '*' }),
  ),
]),
    

void 狀態

Void state

你可以使用 void 狀態來為進入或離開頁面的元素配置轉場。參閱進入和離開檢視的動畫

You can use the void state to configure transitions for an element that is entering or leaving a page. See Animating entering and leaving a view.

組合使用萬用字元和 void 狀態

Combining wildcard and void states

你可以在轉場中組合使用萬用字元和 void 狀態,以觸發那些進入和離開頁面的動畫:

You can combine wildcard and void states in a transition to trigger animations that enter and leave the page:

  • 當元素離開檢視時,就會觸發 * => void 轉場,而不管它離開前處於什麼狀態。

    A transition of * => void applies when the element leaves a view, regardless of what state it was in before it left.

  • 當元素進入檢視時,就會觸發 void => * 轉場,而不管它進入時處於什麼狀態。

    A transition of void => * applies when the element enters a view, regardless of what state it assumes when entering.

  • 萬用字元狀態 * 會匹配任何狀態 —— 包括 void

    The wildcard state * matches to any state, including void.

播放進入和離開檢視時的動畫

Animating entering and leaving a view

本節介紹如何為進入和離開頁面的元素設定動畫。

This section shows how to animate elements entering or leaving a page.

注意:出於我們的目的,我們把元素進入或離開檢視等價於從 DOM 中插入或刪除。

Note: For this example, an element entering or leaving a view is equivalent to being inserted or removed from the DOM.

現在,我們要新增一些新的行為:

Now add a new behavior:

  • 當你把一個英雄新增到英雄列表中時,它看起來是從左側飛進頁面的。

    When you add a hero to the list of heroes, it appears to fly onto the page from the left.

  • 當你從列表中移除一個英雄時,它看起來是從右側飛出去的。

    When you remove a hero from the list, it appears to fly out to the right.

src/app/hero-list-enter-leave.component.ts
      
      animations: [
  trigger('flyInOut', [
    state('in', style({ transform: 'translateX(0)' })),
    transition('void => *', [
      style({ transform: 'translateX(-100%)' }),
      animate(100)
    ]),
    transition('* => void', [
      animate(100, style({ transform: 'translateX(100%)' }))
    ])
  ])
]
    

在上述程式碼中,當 HTML 元素沒有附著在檢視中時,我們就會應用 void 狀態。

In the above code, you applied the void state when the HTML element isn't attached to a view.

:enter 和 :leave 別名

:enter and :leave aliases

:enter:leave 分別是 void => ** => void 的別名。 這些別名供多個動畫函式使用。

:enter and :leave are aliases for the void => * and * => void transitions. These aliases are used by several animation functions.

      
      transition ( ':enter', [ ... ] );  // alias for void => *
transition ( ':leave', [ ... ] );  // alias for * => void
    

定位進入檢視的元素更難,因為它不在 DOM 中。 因此,使用別名 :enter:leave 來定位要從檢視中插入或刪除的 HTML 元素。

It's harder to target an element that is entering a view because it isn't in the DOM yet. So, use the aliases :enter and :leave to target HTML elements that are inserted or removed from a view.

:enter:leave 一起使用 *ngIf*ngFor

Use of *ngIf and *ngFor with :enter and :leave

當任何 *ngIf*ngFor 中的檢視放進頁面中時,會執行 :enter 轉場;當移除這些檢視時,就會執行 :leave 轉場。

The :enter transition runs when any *ngIf or *ngFor views are placed on the page, and :leave runs when those views are removed from the page.

本例子中有一個名叫 myInsertRemoveTrigger 的觸發器,來表示進入和離開動畫。 其 HTML 範本包含下列程式碼。

This example has a special trigger for the enter and leave animation called myInsertRemoveTrigger. The HTML template contains the following code.

src/app/insert-remove.component.html
      
      <div @myInsertRemoveTrigger *ngIf="isShown" class="insert-remove-container">
  <p>The box is inserted</p>
</div>
    

在元件檔案中,:enter 轉場會將初始透明度設定為 0,然後設定動畫,當該元素已經插入檢視中之後,把這個透明度設定為 1。

In the component file, the :enter transition sets an initial opacity of 0, and then animates it to change that opacity to 1 as the element is inserted into the view.

src/app/insert-remove.component.ts
      
      trigger('myInsertRemoveTrigger', [
  transition(':enter', [
    style({ opacity: 0 }),
    animate('100ms', style({ opacity: 1 })),
  ]),
  transition(':leave', [
    animate('100ms', style({ opacity: 0 }))
  ])
]),
    

注意,這個例子並不需要使用 state()

Note that this example doesn't need to use state().

轉場中的 :increment:decrement

:increment and :decrement in transitions

transition() 函式還能接受額外的選擇器值::increment:decrement。當數值增加或減小時,使用這些來啟動轉場。

The transition() function takes additional selector values, :increment and :decrement. Use these to kick off a transition when a numeric value has increased or decreased in value.

注意:下面的例子使用 query()stagger() 方法,它們會在複雜序列中討論。

Note: The following example uses query() and stagger() methods, which is discussed in the complex sequences page.

src/app/hero-list-page.component.ts
      
      trigger('filterAnimation', [
  transition(':enter, * => 0, * => -1', []),
  transition(':increment', [
    query(':enter', [
      style({ opacity: 0, width: '0px' }),
      stagger(50, [
        animate('300ms ease-out', style({ opacity: 1, width: '*' })),
      ]),
    ], { optional: true })
  ]),
  transition(':decrement', [
    query(':leave', [
      stagger(50, [
        animate('300ms ease-out', style({ opacity: 0, width: '0px' })),
      ]),
    ])
  ]),
]),
    

轉場中的邏輯值

Boolean values in transitions

如果某個觸發器以邏輯型的值作為繫結值,那麼就可以使用能與 truefalse10 相比較的 transition() 表示式來匹配這個值。

If a trigger contains a boolean value as a binding value, then this value can be matched using a transition() expression that compares true and false, or 1 and 0.

src/app/open-close.component.html
      
      <div [@openClose]="isOpen ? true : false" class="open-close-container">
</div>
    

在上述程式碼片段中,HTML 範本將 <div> 元素繫結到名為 openClose 的觸發器,其狀態表達式是 isOpen,可能的值為 truefalse。這種方式可以代替建立兩個命名狀態 openclose 的方式。

In the code snippet above, the HTML template binds a <div> element to a trigger named openClose with a status expression of isOpen, and with possible values of true and false. This is an alternative to the practice of creating two named states of open and close.

在元件程式碼中,@Component 元資料下的 animations: 屬性中,當該狀態求值為 true 時(這裡表示 "open"),相關 HTML 元素的高度值為萬用字元樣式 * 或某個預設值。在這種情況下,它會使用此元素開始動畫前的現有高度。當該元素是 "closed" 時,它的高度會從指定的高度運動到 0,這會讓它不可見。

In the component code, in the @Component metadata under the animations: property, when the state evaluates to true (meaning "open" here), the associated HTML element's height is a wildcard style or default. In this case, use whatever height the element already had before the animation started. When the element is "closed," the element animates to a height of 0, which makes it invisible.

src/app/open-close.component.ts
      
      animations: [
  trigger('openClose', [
    state('true', style({ height: '*' })),
    state('false', style({ height: '0px' })),
    transition('false <=> true', animate(500))
  ])
],
    

多重動畫觸發器

Multiple animation triggers

你可以為元件定義多個動畫觸發器並將這些動畫觸發器附著到不同的元素上,這些元素之間的父子關係會影響動畫的執行方式和時機。

You can define more than one animation trigger for a component. You can attach animation triggers to different elements, and the parent-child relationships among the elements affect how and when the animations run.

父-子動畫

Parent-child animations

每次在 Angular 中觸發動畫時,父動畫始終會優先,而子動畫會被阻塞。為了執行子動畫,父動畫必須查詢出包含子動畫的每個元素,然後使用 animateChild()函式來執行它們。

Each time an animation is triggered in Angular, the parent animation always get priority and child animations are blocked. In order for a child animation to run, the parent animation must query each of the elements containing child animations and then allow the animations to run using the animateChild()function.

在某個 HTML 元素上禁用動畫

Disabling an animation on an HTML element

可以把一個名叫 @.disabled 的動畫控制繫結放在 HTML 元素上,以禁用該元素及其子元素上的動畫。當 @.disabled 繫結為 true 時,就會禁止渲染所有動畫。

A special animation control binding called @.disabled can be placed on an HTML element to disable animations on that element, as well as any nested elements. When true, the @.disabled binding prevents all animations from rendering.

下面的程式碼範例展示了如何使用此特性。

The code sample below shows how to use this feature.

      
      <div [@.disabled]="isDisabled">
  <div [@childAnimation]="isOpen ? 'open' : 'closed'"
    class="open-close-container">
    <p>The box is now {{ isOpen ? 'Open' : 'Closed' }}!</p>
  </div>
</div>
    

@.disabled 繫結為 true 時,@childAnimation 觸發器就不會啟動。

When the @.disabled binding is true, the @childAnimation trigger doesn't kick off.

當 HTML 範本中的某個元素使用 @.disabled 禁止了動畫時,也會同時禁止其所有內部元素的動畫。你無法有選擇的單獨禁用單個元素上的多個動畫。

When an element within an HTML template has animations disabled using the @.disabled host binding, animations are disabled on all inner elements as well. You can't selectively disable multiple animations on a single element.

不過,選擇性的子動畫仍然可以用如下方式之一在已禁用的父元素上執行:

However, selective child animations can still be run on a disabled parent in one of the following ways:

  • 父動畫可以使用 query()函式來收集 HTML 範本中位於禁止動畫區域內部的元素。這些元素仍然可以播放動畫。

    A parent animation can use the query()function to collect inner elements located in disabled areas of the HTML template. Those elements can still animate.

  • 子動畫可以被父動畫查詢,並且稍後使用 animateChild() 來播放它。

    A subanimation can be queried by a parent and then later animated with the animateChild() function.

禁用所有動畫

Disabling all animations

要禁用 Angular 應用中的所有動畫,只要把 @.disabled 繫結放在最上層的 Angular 元件上即可。

To disable all animations for an Angular app, place the @.disabled host binding on the topmost Angular component.

src/app/app.component.ts
      
      @Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  animations: [
    slideInAnimation
    // animation triggers go here
  ]
})
export class AppComponent {
  @HostBinding('@.disabled')
  public animationsDisabled = false;
}
    

注意:禁用應用級的動畫在端到端(E2E)測試中是很有用的。

Note: Disabling animations application-wide is useful during end-to-end (E2E) testing.

動畫回呼(Callback)

Animation callbacks

當動畫啟動和終止時,trigger() 函式會發出一些回呼(Callback)。在下面的例子中,我們有一個包含 openClose 觸發器的元件。

The animation trigger() function emits callbacks when it starts and when it finishes. The example below features a component that contains an openClose trigger.

src/app/open-close.component.ts
      
      @Component({
  selector: 'app-open-close',
  animations: [
    trigger('openClose', [
      // ...
    ]),
  ],
  templateUrl: 'open-close.component.html',
  styleUrls: ['open-close.component.css']
})
export class OpenCloseComponent {
  onAnimationEvent( event: AnimationEvent ) {
  }
}
    

在 HTML 範本中,動畫事件可以透過 $event 傳遞回來,比如 @trigger.start@trigger.done,這裡的 trigger 表示所使用的觸發器名字。在我們的例子中,openClose 觸發器將會是這樣的:

In the HTML template, the animation event is passed back via $event, as @trigger.start and @trigger.done, where trigger is the name of the trigger being used. In this example, the trigger openClose appears as follows.

src/app/open-close.component.html
      
      <div [@openClose]="isOpen ? 'open' : 'closed'"
    (@openClose.start)="onAnimationEvent($event)"
    (@openClose.done)="onAnimationEvent($event)"
    class="open-close-container">
</div>
    

動畫回呼(Callback)的潛在用途之一,是用來覆蓋比較慢的 API 呼叫,比如查閱資料庫。例如,你可以建立一個 InProgress 按鈕,讓它擁有自己的迴圈動畫。當後端系統操作完成時,它會播放脈動效果或其它一些視覺動作。

A potential use for animation callbacks could be to cover for a slow API call, such as a database lookup. For example, you could set up the InProgress button to have its own looping animation where it pulsates or does some other visual motion while the backend system operation finishes.

然後,在當前動畫結束時,可以呼叫另一個動畫。比如,當 API 呼叫完成時,按鈕會從 inProgress 狀態程式設計 closed 狀態。

Then, another animation can be called when the current animation finishes. For example, the button goes from the inProgress state to the closed state when the API call is completed.

動畫可以影響終端使用者,讓他覺得操作更快 —— 雖然並沒有。因此,簡單的動畫是保持使用者滿意的一種經濟有效的手段,而不必尋求提高伺服器呼叫的速度或被迫補救那些你無法控制的情況,比如不可靠的網路連線。

An animation can influence an end user to perceive the operation as faster, even when it isn't. Thus, a simple animation can be a cost-effective way to keep users happy, rather than seeking to improve the speed of a server call and having to compensate for circumstances beyond your control, such as an unreliable network connection.

回呼(Callback)可以作為除錯工具,例如與 console.warn() 結合使用,以便在瀏覽器的開發者控制檯中檢視應用的進度。下列程式碼片段為我們原始的雙態按鈕(openclosed)範例建立了控制檯輸出。

Callbacks can serve as a debugging tool, for example in conjunction with console.warn() to view the application's progress in a browser's Developer JavaScript Console. The following code snippet creates console log output for the original example, a button with the two states of open and closed.

src/app/open-close.component.ts
      
      export class OpenCloseComponent {
  onAnimationEvent( event: AnimationEvent ) {
    // openClose is trigger name in this example
    console.warn(`Animation Trigger: ${event.triggerName}`);

    // phaseName is start or done
    console.warn(`Phase: ${event.phaseName}`);

    // in our example, totalTime is 1000 or 1 second
    console.warn(`Total time: ${event.totalTime}`);

    // in our example, fromState is either open or closed
    console.warn(`From: ${event.fromState}`);

    // in our example, toState either open or closed
    console.warn(`To: ${event.toState}`);

    // the HTML element itself, the button in this case
    console.warn(`Element: ${event.element}`);
  }
}
    

關鍵幀動畫

Keyframes

前一節是簡單的雙態轉場。現在,我們要使用關鍵幀動畫建立一個具有多個順序執行步驟的動畫。

The previous section features a simple two-state transition. Now create an animation with multiple steps run in sequence using keyframes.

Angular 的 keyframe() 函式類似於 CSS 中的關鍵幀。關鍵幀允許在單個時間段內進行多種樣式更改。例如,我們的按鈕可以在單個的 2 秒時間段內多次改變顏色,而不是漸隱掉。

Angular's keyframe() function is similar to keyframes in CSS. Keyframes allow several style changes within a single timing segment. For example, the button, instead of fading, could change color several times over a single 2-second timespan.

這些更改顏色的程式碼如下所示:

The code for this color change might look like this.

src/app/status-slider.component.ts
      
      transition('* => active', [
  animate('2s', keyframes([
    style({ backgroundColor: 'blue' }),
    style({ backgroundColor: 'red' }),
    style({ backgroundColor: 'orange' })
  ]))
    

偏移

Offset

關鍵幀包括一個用來定義動畫中每個樣式何時開始更改的偏移(offset)屬性。偏移是個 0 到 1 之間的相對值,分別標記動畫的開始和結束時間,並且只要使用了它,就要同樣應用於這個關鍵幀的每個步驟。

Keyframes include an offset that defines the point in the animation where each style change occurs. Offsets are relative measures from zero to one, marking the beginning and end of the animation, respectively and should be applied to each of the keyframe's steps if used at least once.

定義關鍵幀的偏移量是可選的。如果省略它們,就會自動分配均勻間隔的偏移。例如,三個沒有預定義偏移的關鍵幀會分別使用 0、0.5、1 作為偏移。在上面的例子中,還可以為中間的轉場指定偏移量 0.8。程式碼如下:

Defining offsets for keyframes is optional. If you omit them, evenly spaced offsets are automatically assigned. For example, three keyframes without predefined offsets receive offsets of 0, 0.5, and 1. Specifying an offset of 0.8 for the middle transition in the above example might look like this.

帶有指定偏移量的程式碼如下:

The code with offsets specified would be as follows.

src/app/status-slider.component.ts
      
      transition('* => active', [
  animate('2s', keyframes([
    style({ backgroundColor: 'blue', offset: 0}),
    style({ backgroundColor: 'red', offset: 0.8}),
    style({ backgroundColor: 'orange', offset: 1.0})
  ])),
]),
transition('* => inactive', [
  animate('2s', keyframes([
    style({ backgroundColor: 'orange', offset: 0}),
    style({ backgroundColor: 'red', offset: 0.2}),
    style({ backgroundColor: 'blue', offset: 1.0})
  ]))
]),
    

你可以在單個動畫中組合使用 durationdelayeasing 來定義關鍵幀。

You can combine keyframes with duration, delay, and easing within a single animation.

帶脈動效果的關鍵幀

Keyframes with a pulsation

透過在整個動畫中定義特定偏移處的樣式,可以使用關鍵幀在動畫中建立脈動效果。

Use keyframes to create a pulse effect in your animations by defining styles at specific offset throughout the animation.

下面是使用關鍵幀建立脈動效果的例子:

Here's an example of using keyframes to create a pulse effect:

  • 原始的 openclosed 狀態(包括其原始的高度、顏色和透明度)會在一秒鐘內逐漸發生變化。

    The original open and closed states, with the original changes in height, color, and opacity, occurring over a timeframe of 1 second.

  • 插在中間的關鍵幀序列會導致該按鈕在一秒鐘內出現不規則的脈動。

    A keyframes sequence inserted in the middle that causes the button to appear to pulsate irregularly over the course of that same 1-second timeframe.

此動畫的程式碼片段是這樣的:

The code snippet for this animation might look like this.

src/app/open-close.component.ts
      
      trigger('openClose', [
  state('open', style({
    height: '200px',
    opacity: 1,
    backgroundColor: 'yellow'
  })),
  state('close', style({
    height: '100px',
    opacity: 0.5,
    backgroundColor: 'green'
  })),
  // ...
  transition('* => *', [
    animate('1s', keyframes ( [
      style({ opacity: 0.1, offset: 0.1 }),
      style({ opacity: 0.6, offset: 0.2 }),
      style({ opacity: 1,   offset: 0.5 }),
      style({ opacity: 0.2, offset: 0.7 })
    ]))
  ])
])
    

可動的屬性與單位

Animatable properties and units

Angular 的動畫支援是基於 Web 動畫的,所以你可以動瀏覽器認為可動(animatable)的任意屬性。包括位置、大小、變形、顏色、邊框等。W3C 在 CSS 轉場頁也維護了一個可動屬性的列表。

Angular's animation support builds on top of web animations, so you can animate any property that the browser considers animatable. This includes positions, sizes, transforms, colors, borders, and more. The W3C maintains a list of animatable properties on its CSS Transitions page.

對於帶有數值的位置屬性,可以把值作為字串(別忘了帶引號)並使用適當的字尾來定義其單位:

For positional properties with a numeric value, define a unit by providing the value as a string, in quotes, with the appropriate suffix:

  • 50 畫素:'50px'

    50 pixels: '50px'

  • 相對字型大小:'3em'

    Relative font size: '3em'

  • 百分比:'100%'

    Percentage: '100%'

如果在指定尺寸時未提供單位,則 Angular 將使用預設單位畫素(px)。把 50 畫素表示為 50'50px' 是一樣的。

If you don't provide a unit when specifying dimension, Angular assumes a default unit of pixels, or px. Expressing 50 pixels as 50 is the same as saying '50px'.

使用萬用字元自動計算屬性

Automatic property calculation with wildcards

有時你在執行之前並不知道某個樣式的屬性值。比如,元素的寬度和高度通常取決於其內容和螢幕大小。在使用 CSS 動畫時,這些屬性通常會具有挑戰性(譯註:因為 CSS 動畫不支援自動確定寬高)。

Sometimes you don't know the value of a dimensional style property until runtime. For example, elements often have widths and heights that depend on their content and the screen size. These properties are often challenging to animate using CSS.

這些情況下,你可以在 style() 中指定萬用字元 * 屬性,以便在執行期間計算該屬性的值,然後把它插入到動畫中。

In these cases, you can use a special wildcard * property value under style(), so that the value of that particular style property is computed at runtime and then plugged into the animation.

下面的例子中有一個名叫 shrinkOut 的觸發器,它會在 HTML 元素離開頁面時使用。該動畫會使用它離開之前的任意高度,並從該高度動畫到 0。

The following example has a trigger called shrinkOut, used when an HTML element leaves the page. The animation takes whatever height the element has before it leaves, and animates from that height to zero.

src/app/hero-list-auto.component.ts
      
      animations: [
  trigger('shrinkOut', [
    state('in', style({ height: '*' })),
    transition('* => void', [
      style({ height: '*' }),
      animate(250, style({ height: 0 }))
    ])
  ])
]
    

關鍵幀動畫總結

Keyframes summary

Angular 中的 keyframes() 函式允許你在單個轉場中指定多個臨時樣式,並使用可選的偏移量來定義動畫中每次樣式變化的發生時機。

The keyframes() function in Angular allows you to specify multiple interim styles within a single transition, with an optional offset to define the point in the animation where each style change occurs.

Angular 動畫的更多知識

More on Angular animations

你可能還對下列內容感興趣:

You may also be interested in the following: