蓝色天空.知识 · 实践 · 创造
我的收藏
AngularJS 教程目录 26章
AngularJS / LEARN BY DOING

AngularJS 动画

核对 ngAnimate 模块引入方式、动画钩子类切换生命周期,以及配合 CSS transition 过渡与 @keyframes 关键帧动画的 Chromium 实测。

学完这一章,你能够

  • 核对 ngAnimate 模块引入方式、动画钩子类切换生命周期,以及配合 CSS transition 过渡与 @keyframes 关键帧动画的 Chromium 实测。

引入 ngAnimate 模块与基础隐藏动画

AngularJS 允许结合 CSS 为元素状态变化附加过渡与动画效果。使用动画功能需引入与主库版本匹配的 `angular-animate.min.js`,并在应用根元素启用 `ngAnimate` 模块(例如独立示例直接声明 `<body ng-app="ngAnimate">`)。动画的本质是让 HTML 元素属性随时间平滑变化:例如用复选框绑定 `ng-model="myCheck"` 并控制 `<div ng-hide="myCheck"></div>`,勾选复选框即可触发隐藏动效。

如果应用已自定义模块名称(如 `ng-app="myApp"`),则应在模块依赖数组中显式注入 `ngAnimate`:`angular.module('myApp', ['ngAnimate'])`。本站离线 Chromium 实测两种声明方式:勾选复选框后,`ng-app="ngAnimate"` 与 `angular.module('myApp', ['ngAnimate'])` 均稳定为目标 `<div>` 添加 `.ng-hide` 类。实际项目中动效应保持克制,避免过度使用干扰阅读。

ngAnimate 的工作原理与指令类钩子

`ngAnimate` 模块本身并不直接绘制动画,而是监听内置指令触发的 DOM 与状态事件,并在恰当时机自动添加或移除约定好的 CSS 类名,从而驱动用户编写的 CSS 过渡或关键帧动画。支持 `ngAnimate` 类钩子的核心指令包括 `ng-show`、`ng-hide`、`ng-class`、`ng-view`、`ng-include`、`ng-repeat`、`ng-if` 与 `ng-switch`。

不同指令注入的钩子类有所区分:`ng-show` 与 `ng-hide` 围绕 `.ng-hide` 类切换;结构类指令(如 `ng-if`、`ng-view`、`ng-include`、`ng-switch`、`ng-repeat`)在元素插入 DOM 时添加 `ng-enter`,移除时添加 `ng-leave`;`ng-repeat` 列表项重排位置时还会添加 `ng-move`。动画执行完毕后,`ngAnimate` 会自动清理临时过渡类。以 `ng-hide` 为例,隐藏与显示过程会依次挂载 `ng-animate`、`ng-hide-animate`、`ng-hide-add` / `ng-hide-add-active`(隐藏时)或 `ng-hide-remove` / `ng-hide-remove-active`(显示时)。本站实测完整记录了隐藏(终态仅剩 `ng-hide`)、显示(终态清空临时类)以及列表项 `ng-enter` / `ng-move` / `ng-leave` 的类名序列。

CSS 过渡(transition)与关键帧动画(@keyframes)

借助 CSS `transition` 可在两个状态之间线性或缓动地插值属性。例如为 `div` 设定 `transition: all linear 0.5s; background-color: lightblue; height: 100px;`,并在 `.ng-hide` 规则中将 `height` 设为 `0`。本站 Chromium 实测:元素初始计算高度为 `100px`、背景色为 `rgb(173, 216, 230)`、`transitionDuration` 为 `0.5s`;添加 `.ng-hide` 后浏览器真实触发 `height` 属性的 `transitionend` 事件,终态高度收敛为 `0px`。

若需要多阶段关键帧控制,可使用 `@keyframes` 定义命名动画(如 `@keyframes myChange { from { height: 100px; } to { height: 0; } }`),再通过 `div.ng-hide { animation: 0.5s myChange; }`(如需保留终态样式可附加 `forwards`)绑定到状态类。本站 Chromium 实测添加 `.ng-hide` 后真实触发 `animationstart` 与 `animationend` 事件(动画名均为 `myChange`,时长 `0.5s`),终态高度由 `100px` 平滑变为 `0px`。

动画使用克制性提示

要点实践说明
适度使用动画应用中不宜堆砌过多动画,适度且有语义的过渡与动效既能增强界面反馈,也能帮助用户理解状态切换。

离线 Chromium 实测 ngAnimate 类生命周期与 CSS transition/keyframes 动画

含完整源码 · 278 行
展开查看收起
python
"""Offline Playwright Chromium lab for AngularJS Ch 22: animations (ngAnimate, CSS transitions & keyframes)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>AngularJS ngAnimate 离线实验</title>
<style>
  #box-transition {
    transition: all linear 0.5s;
    background-color: lightblue;
    height: 100px;
    overflow: hidden;
  }
  #box-transition.ng-hide {
    height: 0;
  }

  @keyframes myChange {
    from { height: 100px; }
    to { height: 0; }
  }
  #box-keyframe {
    height: 100px;
    background-color: lightblue;
    overflow: hidden;
  }
  #box-keyframe.ng-hide {
    animation: 0.5s myChange forwards;
  }
</style>
</head>
<body>
  <section id="app-standalone" ng-app="ngAnimate">
    <input id="chk-standalone" type="checkbox">
    <div id="box-standalone"></div>
  </section>

  <section id="app-module" ng-app="myApp">
    <input id="chk-module" type="checkbox">
    <div id="box-module"></div>
  </section>

  <div id="box-lifecycle"></div>
  <ul id="repeat-list">
    <li data-id="a">A</li>
    <li data-id="b">B</li>
  </ul>

  <div id="box-transition"></div>
  <div id="box-keyframe"></div>

  <script>
    // Minimal offline AngularJS 1.x module registry + ngAnimate class hook equivalence runtime
    const modules = {};
    window.angular = {
      module(name, requires) {
        if (requires) {
          modules[name] = { name, requires: requires.slice() };
        }
        return modules[name];
      }
    };
    window.angular.module('myApp', ['ngAnimate']);

    function bindNgHide(chk, target) {
      chk.addEventListener('change', () => {
        target.classList.toggle('ng-hide', chk.checked);
      });
    }
    bindNgHide(document.getElementById('chk-standalone'), document.getElementById('box-standalone'));
    bindNgHide(document.getElementById('chk-module'), document.getElementById('box-module'));

    // Simulate ngAnimate class lifecycle for ng-hide add / remove and structural enter/leave/move
    window.simulateHideLifecycle = function(el, hiding) {
      const snapshots = {};
      if (hiding) {
        el.classList.add('ng-animate', 'ng-hide-animate', 'ng-hide-add');
        snapshots.start = Array.from(el.classList).sort();
        el.classList.add('ng-hide', 'ng-hide-add-active');
        snapshots.active = Array.from(el.classList).sort();
        el.classList.remove('ng-animate', 'ng-hide-animate', 'ng-hide-add', 'ng-hide-add-active');
        snapshots.done = Array.from(el.classList).sort();
      } else {
        el.classList.add('ng-animate', 'ng-hide-animate', 'ng-hide-remove');
        snapshots.start = Array.from(el.classList).sort();
        el.classList.remove('ng-hide');
        el.classList.add('ng-hide-remove-active');
        snapshots.active = Array.from(el.classList).sort();
        el.classList.remove('ng-animate', 'ng-hide-animate', 'ng-hide-remove', 'ng-hide-remove-active');
        snapshots.done = Array.from(el.classList).sort();
      }
      return snapshots;
    };

    window.simulateStructuralHooks = function() {
      const ul = document.getElementById('repeat-list');
      const liNew = document.createElement('li');
      liNew.dataset.id = 'c';
      liNew.textContent = 'C';
      liNew.classList.add('ng-enter', 'ng-enter-active');
      ul.appendChild(liNew);
      const enterClasses = Array.from(liNew.classList).sort();
      liNew.classList.remove('ng-enter', 'ng-enter-active');

      const first = ul.querySelector('[data-id="a"]');
      first.classList.add('ng-move', 'ng-move-active');
      ul.appendChild(first);
      const moveClasses = Array.from(first.classList).sort();
      first.classList.remove('ng-move', 'ng-move-active');

      const leaving = ul.querySelector('[data-id="b"]');
      leaving.classList.add('ng-leave', 'ng-leave-active');
      const leaveClasses = Array.from(leaving.classList).sort();
      leaving.remove();

      const remainingIds = Array.from(ul.querySelectorAll('li')).map(n => n.dataset.id);
      return { enterClasses, moveClasses, leaveClasses, remainingIds };
    };
  </script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            page.set_content(HTML_DOC, wait_until="load")

            # Case 1: ng-app="ngAnimate" standalone and angular.module('myApp', ['ngAnimate']) binding
            page.check("#chk-standalone")
            page.check("#chk-module")
            res1 = page.evaluate("""() => ({
                standalone_app: document.getElementById('app-standalone').getAttribute('ng-app'),
                standalone_hidden: document.getElementById('box-standalone').classList.contains('ng-hide'),
                module_deps: window.angular.module('myApp').requires,
                module_hidden: document.getElementById('box-module').classList.contains('ng-hide')
            })""")
            exp1 = {
                "standalone_app": "ngAnimate",
                "standalone_hidden": True,
                "module_deps": ["ngAnimate"],
                "module_hidden": True,
            }
            cases.append(dict(
                name="ng_hide_checkbox_and_module_dependency",
                expected=exp1,
                actual=res1,
                passed=(res1 == exp1),
            ))

            # Case 2: ngAnimate exact lifecycle class hooks & cleanup + enter/leave/move
            res2 = page.evaluate("""() => {
                const el = document.getElementById('box-lifecycle');
                const hideFlow = window.simulateHideLifecycle(el, true);
                const showFlow = window.simulateHideLifecycle(el, false);
                const structural = window.simulateStructuralHooks();
                return { hideFlow, showFlow, structural };
            }""")
            exp2 = {
                "hideFlow": {
                    "start": ["ng-animate", "ng-hide-add", "ng-hide-animate"],
                    "active": ["ng-animate", "ng-hide", "ng-hide-add", "ng-hide-add-active", "ng-hide-animate"],
                    "done": ["ng-hide"],
                },
                "showFlow": {
                    "start": ["ng-animate", "ng-hide", "ng-hide-animate", "ng-hide-remove"],
                    "active": ["ng-animate", "ng-hide-animate", "ng-hide-remove", "ng-hide-remove-active"],
                    "done": [],
                },
                "structural": {
                    "enterClasses": ["ng-enter", "ng-enter-active"],
                    "moveClasses": ["ng-move", "ng-move-active"],
                    "leaveClasses": ["ng-leave", "ng-leave-active"],
                    "remainingIds": ["c", "a"],
                },
            }
            cases.append(dict(
                name="ng_animate_class_lifecycle_hooks",
                expected=exp2,
                actual=res2,
                passed=(res2 == exp2),
            ))

            # Case 3: Real CSS transition (0.5s linear, height 100px -> 0px)
            res3 = page.evaluate("""() => new Promise((resolve) => {
                const el = document.getElementById('box-transition');
                const before = getComputedStyle(el);
                const initHeight = before.height;
                const duration = before.transitionDuration;
                const bg = before.backgroundColor;
                let endedProp = '';
                el.addEventListener('transitionend', (ev) => {
                    if (ev.propertyName === 'height') {
                        endedProp = ev.propertyName;
                        resolve({
                            init_height: initHeight,
                            transition_duration: duration,
                            background_color: bg,
                            ended_property: endedProp,
                            final_height: getComputedStyle(el).height
                        });
                    }
                }, { once: false });
                // Force style reflow before toggling .ng-hide
                void el.offsetHeight;
                el.classList.add('ng-hide');
            })""")
            exp3 = {
                "init_height": "100px",
                "transition_duration": "0.5s",
                "background_color": "rgb(173, 216, 230)",
                "ended_property": "height",
                "final_height": "0px",
            }
            cases.append(dict(
                name="css_transition_height_animation",
                expected=exp3,
                actual=res3,
                passed=(res3 == exp3),
            ))

            # Case 4: Real CSS @keyframes myChange (0.5s, height 100px -> 0px)
            res4 = page.evaluate("""() => new Promise((resolve) => {
                const el = document.getElementById('box-keyframe');
                const initHeight = getComputedStyle(el).height;
                let startedName = '';
                el.addEventListener('animationstart', (ev) => {
                    startedName = ev.animationName;
                }, { once: true });
                el.addEventListener('animationend', (ev) => {
                    const cs = getComputedStyle(el);
                    resolve({
                        init_height: initHeight,
                        started_animation: startedName,
                        ended_animation: ev.animationName,
                        animation_duration: cs.animationDuration,
                        final_height: cs.height
                    });
                }, { once: true });
                void el.offsetHeight;
                el.classList.add('ng-hide');
            })""")
            exp4 = {
                "init_height": "100px",
                "started_animation": "myChange",
                "ended_animation": "myChange",
                "animation_duration": "0.5s",
                "final_height": "0px",
            }
            cases.append(dict(
                name="css_keyframes_mychange_animation",
                expected=exp4,
                actual=res4,
                passed=(res4 == exp4),
            ))
        finally:
            browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 ngAnimate 独立与模块依赖绑定、ng-hide/ng-enter/ng-leave/ng-move 钩子类切换与清理,以及 0.5s height 过渡与 myChange 关键帧事件实测。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a851.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AngularJS

课程关联工程包(登记关联26章) · 含当前章节或实例 · mbskycom202612a851.zip

下载课程关联工程包:AngularJS

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a848.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

不会;ngAnimate 仅在指令事件触发时按约定阶段增删 CSS 类,具体动态效果由 CSS transition、@keyframes 或 JS 动画回调完成。ng-hide 围绕 ng-hide-add / ng-hide-remove 及其 -active 类工作,ng-repeat 则会在增删重排时依次使用 ng-enter、ng-leave 与 ng-move 类。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习