蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery · 本地阅读预览
教程 / 前端开发 / jQuery

jQuery 动画

核对 animate() 自定义动画语法、position 非 static 前置条件、多属性与驼峰命名、+=/-= 相对值、toggle 预定义值以及内部动画队列顺序执行。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

animate() 基础语法与定位前置条件

`$(selector).animate({params}, speed, callback)` 用于创建任意数值型 CSS 属性的自定义动画:必需的 `params` 对象声明目标 CSS 属性映射,可选 `speed` 指定时长(`"slow"`、`"fast"` 或毫秒),可选 `callback` 在动画完成后执行。若要通过 `left`/`top` 移动元素位置,必须先将元素 CSS `position` 设为 `relative`、`fixed` 或 `absolute`,默认 `static` 元素不会发生位移。本站离线 Chromium 对照实测:同时对 `#static-box`(`position: static`)与 `#rel-box`(`position: relative`)执行 `animate({left: '250px'})`,`#rel-box` 实测横坐标右移 `+250px`(计算 `left: 250px`),而 `#static-box` 实际水平位移为 `0px`。

同时操作多属性、驼峰命名与色彩动画限制

`params` 对象可一次声明多个属性以同步插值变化。书写属性名时,凡含连字符的 CSS 属性都必须改用 Camel 驼峰标记法(如 `paddingLeft`、`marginRight`、`fontSize`)。此外,核心 jQuery 库不包含颜色(如 `backgroundColor`、`color`)过渡动画,若需色彩插值须另行引入官方 Color 插件或改用 CSS Transitions。本站离线实测对 `#multi-box` 同步执行 `{left: '250px', opacity: '0.5', height: '150px', width: '150px', paddingLeft: '24px'}`,完成后五项计算样式精确收敛为 `left=250px`、`opacity=0.5`、`height=150px`、`width=150px`、`paddingLeft=24px`。

相对值(+= / -=)与预定义值(show / hide / toggle)

属性值前缀加上 `+=` 或 `-=` 即可基于元素当前计算值进行增量或减量动画。本站离线实测对初始 `100px × 100px` 的 `#relsize-box` 连续两次执行 `{left: '250px', height: '+=150px', width: '+=150px'}`,尺寸依次累加至 `250px × 250px` 与 `400px × 400px`;再执行 `{height: '-=50px', width: '-=50px'}` 后精确缩回 `350px × 350px`。

`animate()` 还支持把 `height`、`width` 等属性的目标值设为预定义关键字 `"show"`、`"hide"` 或 `"toggle"`。本站离线实测对 `100px` 高的 `#toggle-box` 两次执行 `animate({height: 'toggle'})`:首次收起为 `display: none`,第二次恢复为 `display: block, height: 100px`。

动画队列功能:多步顺序执行

jQuery 默认为每个元素维护内部动画队列(`fx` 队列):对同一元素连续编写多个 `animate()` 调用时,不会并发覆盖,而是按调用顺序逐一排期执行。本站离线实测两组经典队列:对 `#queue-box` 依次排队 4 步(高 300px/透明 0.4 → 宽 300px/透明 0.8 → 高 100px/透明 0.4 → 宽 100px/透明 0.8),回调按序记录 `['step1:300px', 'step2:300px', 'step3:100px', 'step4:100px']` 并最终收束于 `100px × 100px, opacity: 0.8`;对 `#text-box` 先右移 `100px` 再将 `fontSize` 放大至 `3em`(16px 基准下为 `48px`),回调严格按序记录 `['text1:100px', 'text2:48px']`。

位移动画前置条件提示

提示主题核心说明
为何必须设置 position?所有 HTML 元素默认 position 为 static,无法响应 left/right/top/bottom 偏移;执行位移动画前须显式设置 position: relative、fixed 或 absolute。

animate() 属性命名与色彩限制提示

提示主题核心说明
属性书写规范与颜色动画animate() 仅对数值型属性生效且要求连字符属性改写为 Camel 驼峰式(如 paddingLeft、marginRight);核心库不含色彩动画,颜色过渡需另引入 Color 插件或使用 CSS 过渡。

运行定位前置条件、多属性驼峰、+=/-= 相对值、toggle 预定义值与队列动画实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery Chapter 10 (animate)."""
import json
from playwright.sync_api import sync_playwright

MINI_JQ = r"""
(function (global) {
  function parseSpeed(speed) {
    if (speed === undefined || speed === null) return 400;
    if (speed === "slow") return 600;
    if (speed === "fast") return 200;
    if (typeof speed === "number") return Math.max(0, speed);
    return 400;
  }
  function camelToKebab(prop) {
    return prop.replace(/[A-Z]/g, function (m) { return "-" + m.toLowerCase(); });
  }
  function resolveValue(el, prop, rawVal) {
    const str = String(rawVal).trim();
    const rel = str.match(/^([+-])=([0-9.]+)(px|em|%)?$/);
    if (rel) {
      const sign = rel[1] === "+" ? 1 : -1;
      const delta = parseFloat(rel[2]);
      const unit = rel[3] || "px";
      const cur = parseFloat(getComputedStyle(el)[prop]) || 0;
      return (cur + sign * delta) + unit;
    }
    return str;
  }
  function runNext(el) {
    const q = el.__jqQueue || [];
    if (!q.length) {
      el.__jqRunning = false;
      return;
    }
    el.__jqRunning = true;
    const task = q.shift();
    const { params, ms, cb } = task;
    const keys = Object.keys(params);
    let hideAfter = false;
    const resolved = {};
    keys.forEach(function (k) {
      const v = String(params[k]).trim();
      if ((k === "height" || k === "width") && (v === "toggle" || v === "hide" || v === "show")) {
        const isHidden = getComputedStyle(el).display === "none";
        if (v === "hide" || (v === "toggle" && !isHidden)) {
          el.dataset["saved_" + k] = getComputedStyle(el)[k];
          el.style[k] = getComputedStyle(el)[k];
          resolved[k] = "0px";
          hideAfter = true;
        } else {
          el.style.display = "block";
          el.style[k] = "0px";
          resolved[k] = el.dataset["saved_" + k] || "100px";
        }
      } else {
        resolved[k] = resolveValue(el, k, v);
      }
    });
    void el.offsetHeight;
    el.style.transition = keys.map(function (k) { return camelToKebab(k) + " " + ms + "ms ease"; }).join(", ");
    keys.forEach(function (k) { el.style[k] = resolved[k]; });
    setTimeout(function () {
      el.style.transition = "none";
      void el.offsetHeight;
      el.style.transition = "";
      if (hideAfter) el.style.display = "none";
      if (typeof cb === "function") cb.call(el);
      runNext(el);
    }, ms + 35);
  }
  function JQ(elements) {
    this.elements = elements;
    this.length = elements.length;
  }
  JQ.prototype.each = function (fn) {
    this.elements.forEach(function (el, idx) { fn.call(el, idx, el); });
    return this;
  };
  JQ.prototype.ready = function (fn) {
    if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", fn);
    else fn();
    return this;
  };
  JQ.prototype.click = function (fn) {
    return this.each(function (_, el) {
      el.addEventListener("click", function (ev) { fn.call(el, ev); });
    });
  };
  JQ.prototype.animate = function (params, speed, callback) {
    const ms = typeof speed === "function" ? 400 : parseSpeed(speed);
    const cb = typeof speed === "function" ? speed : callback;
    return this.each(function (_, el) {
      el.__jqQueue = el.__jqQueue || [];
      el.__jqQueue.push({ params: params, ms: ms, cb: cb });
      if (!el.__jqRunning) runNext(el);
    });
  };
  function $(selector) {
    if (typeof selector === "function") return new JQ([document]).ready(selector);
    if (selector === document || selector instanceof Element) return new JQ([selector]);
    if (typeof selector === "string") return new JQ(Array.from(document.querySelectorAll(selector)));
    return new JQ([]);
  }
  $.fn = JQ.prototype;
  $.fn.jquery = "3.7.1-offline-lab";
  global.$ = global.jQuery = $;
})(window);
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>jQuery 动画离线实验</title>
  <style>
    html {{ font-size: 16px; }}
    body {{ margin: 0; font-size: 16px; }}
    .box {{ width: 100px; height: 100px; background: #98bf21; box-sizing: content-box; }}
    #static-box {{ position: static; }}
    #rel-box, #multi-box, #relsize-box, #queue-box, #text-box {{ position: relative; left: 0px; }}
  </style>
  <script>{MINI_JQ}</script>
  <script>
    window.__qLog = [];
    window.__flags = {{}};
    $(document).ready(function () {{
      $("#btn-pos").click(function () {{
        $("#static-box").animate({{ left: "250px" }}, 50, function () {{ window.__flags.staticDone = true; }});
        $("#rel-box").animate({{ left: "250px" }}, 50, function () {{ window.__flags.relDone = true; }});
      }});
      $("#btn-multi").click(function () {{
        $("#multi-box").animate({{
          left: "250px",
          opacity: "0.5",
          height: "150px",
          width: "150px",
          paddingLeft: "24px"
        }}, 50, function () {{ window.__flags.multiDone = true; }});
      }});
      $("#btn-relsize").click(function () {{
        $("#relsize-box").animate({{
          left: "250px",
          height: "+=150px",
          width: "+=150px"
        }}, 40, function () {{ window.__flags.relsizeCount = (window.__flags.relsizeCount || 0) + 1; }});
      }});
      $("#btn-shrink").click(function () {{
        $("#relsize-box").animate({{
          height: "-=50px",
          width: "-=50px"
        }}, 40, function () {{ window.__flags.shrinkDone = true; }});
      }});
      $("#btn-toggle").click(function () {{
        $("#toggle-box").animate({{ height: "toggle" }}, 40, function () {{
          window.__flags.toggleCount = (window.__flags.toggleCount || 0) + 1;
        }});
      }});
      $("#btn-queue").click(function () {{
        const div = $("#queue-box");
        div.animate({{ height: "300px", opacity: "0.4" }}, 40, function () {{ window.__qLog.push("step1:" + getComputedStyle(this).height); }});
        div.animate({{ width: "300px", opacity: "0.8" }}, 40, function () {{ window.__qLog.push("step2:" + getComputedStyle(this).width); }});
        div.animate({{ height: "100px", opacity: "0.4" }}, 40, function () {{ window.__qLog.push("step3:" + getComputedStyle(this).height); }});
        div.animate({{ width: "100px", opacity: "0.8" }}, 40, function () {{ window.__qLog.push("step4:" + getComputedStyle(this).width); }});

        const tdiv = $("#text-box");
        tdiv.animate({{ left: "100px" }}, 40, function () {{ window.__qLog.push("text1:" + getComputedStyle(this).left); }});
        tdiv.animate({{ fontSize: "3em" }}, 40, function () {{ window.__qLog.push("text2:" + getComputedStyle(this).fontSize); }});
      }});
    }});
  </script>
</head>
<body>
  <div id="static-box" class="box">static</div>
  <div id="rel-box" class="box">relative</div>
  <button id="btn-pos" type="button">位置动画</button>

  <div id="multi-box" class="box">multi</div>
  <button id="btn-multi" type="button">多属性动画</button>

  <div id="relsize-box" class="box">relsize</div>
  <button id="btn-relsize" type="button">相对增加</button>
  <button id="btn-shrink" type="button">相对减少</button>

  <div id="toggle-box" class="box">toggle</div>
  <button id="btn-toggle" type="button">预定义切换</button>

  <div id="queue-box" class="box">queue</div>
  <div id="text-box" class="box">HELLO</div>
  <button id="btn-queue" type="button">队列动画</button>
</body>
</html>
"""


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


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

            # Case 1: Single property left:250px & position:static vs relative
            before_pos = page.evaluate(
                """() => ({
                    static_x: document.getElementById("static-box").getBoundingClientRect().left,
                    rel_x: document.getElementById("rel-box").getBoundingClientRect().left
                })"""
            )
            page.locator("#btn-pos").click()
            page.wait_for_function("() => window.__flags.staticDone && window.__flags.relDone", timeout=3000)
            act1 = page.evaluate(
                """(bp) => ({
                    static_delta_x: Math.round(document.getElementById("static-box").getBoundingClientRect().left - bp.static_x),
                    rel_delta_x: Math.round(document.getElementById("rel-box").getBoundingClientRect().left - bp.rel_x),
                    rel_computed_left: getComputedStyle(document.getElementById("rel-box")).left
                })""",
                before_pos,
            )
            exp1 = {"static_delta_x": 0, "rel_delta_x": 250, "rel_computed_left": "250px"}
            cases.append(dict(name="single_prop_and_position_requirement", passed=(act1 == exp1), expected=exp1, actual=act1))

            # Case 2: Multiple CSS properties + camelCase (paddingLeft)
            page.locator("#btn-multi").click()
            page.wait_for_function("() => window.__flags.multiDone === true", timeout=3000)
            act2 = page.evaluate(
                """() => {
                    const cs = getComputedStyle(document.getElementById("multi-box"));
                    return {
                        left: cs.left,
                        opacity: Number(Number(cs.opacity).toFixed(2)),
                        height: cs.height,
                        width: cs.width,
                        paddingLeft: cs.paddingLeft
                    };
                }"""
            )
            exp2 = {"left": "250px", "opacity": 0.5, "height": "150px", "width": "150px", "paddingLeft": "24px"}
            cases.append(dict(name="multi_property_and_camelcase", passed=(act2 == exp2), expected=exp2, actual=act2))

            # Case 3: Relative values +=150px twice then -=50px
            page.locator("#btn-relsize").click()
            page.wait_for_function("() => window.__flags.relsizeCount === 1", timeout=3000)
            s1 = page.evaluate(
                "() => ({ w: getComputedStyle(document.getElementById('relsize-box')).width, h: getComputedStyle(document.getElementById('relsize-box')).height })"
            )
            page.locator("#btn-relsize").click()
            page.wait_for_function("() => window.__flags.relsizeCount === 2", timeout=3000)
            s2 = page.evaluate(
                "() => ({ w: getComputedStyle(document.getElementById('relsize-box')).width, h: getComputedStyle(document.getElementById('relsize-box')).height })"
            )
            page.locator("#btn-shrink").click()
            page.wait_for_function("() => window.__flags.shrinkDone === true", timeout=3000)
            s3 = page.evaluate(
                "() => ({ w: getComputedStyle(document.getElementById('relsize-box')).width, h: getComputedStyle(document.getElementById('relsize-box')).height })"
            )
            act3 = {"after_plus1": s1, "after_plus2": s2, "after_minus50": s3}
            exp3 = {
                "after_plus1": {"w": "250px", "h": "250px"},
                "after_plus2": {"w": "400px", "h": "400px"},
                "after_minus50": {"w": "350px", "h": "350px"},
            }
            cases.append(dict(name="relative_plus_minus_values", passed=(act3 == exp3), expected=exp3, actual=act3))

            # Case 4: Predefined value height:'toggle'
            page.locator("#btn-toggle").click()
            page.wait_for_function("() => window.__flags.toggleCount === 1", timeout=3000)
            t1 = page.evaluate("() => getComputedStyle(document.getElementById('toggle-box')).display")
            page.locator("#btn-toggle").click()
            page.wait_for_function("() => window.__flags.toggleCount === 2", timeout=3000)
            t2 = page.evaluate(
                "() => ({ display: getComputedStyle(document.getElementById('toggle-box')).display, height: getComputedStyle(document.getElementById('toggle-box')).height })"
            )
            act4 = {"after_click1_display": t1, "after_click2": t2}
            exp4 = {"after_click1_display": "none", "after_click2": {"display": "block", "height": "100px"}}
            cases.append(dict(name="predefined_toggle_height", passed=(act4 == exp4), expected=exp4, actual=act4))

            # Case 5: Sequential animation queue (4-step box + 2-step move/fontSize)
            page.locator("#btn-queue").click()
            page.wait_for_function("() => window.__qLog.filter(x => x.startsWith('step')).length === 4 && window.__qLog.filter(x => x.startsWith('text')).length === 2", timeout=4000)
            act5 = page.evaluate(
                """() => {
                    const q = getComputedStyle(document.getElementById("queue-box"));
                    const t = getComputedStyle(document.getElementById("text-box"));
                    return {
                        box_steps: window.__qLog.filter(x => x.startsWith("step")),
                        text_steps: window.__qLog.filter(x => x.startsWith("text")),
                        final_box: { width: q.width, height: q.height, opacity: Number(Number(q.opacity).toFixed(2)) },
                        final_text: { left: t.left, fontSize: t.fontSize }
                    };
                }"""
            )
            exp5 = {
                "box_steps": ["step1:300px", "step2:300px", "step3:100px", "step4:100px"],
                "text_steps": ["text1:100px", "text2:48px"],
                "final_box": {"width": "100px", "height": "100px", "opacity": 0.8},
                "final_text": {"left": "100px", "fontSize": "48px"},
            }
            cases.append(dict(name="animation_queue_sequential", passed=(act5 == exp5), expected=exp5, actual=act5))
        finally:
            browser.close()

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在离线 Chromium 中核对 static(delta=0) 与 relative(delta=+250px) 对照、五属性同步收敛、100→250→400→350px 相对累积、height:'toggle' 往返,以及 4 步与 2 步队列顺序。
运行定位前置条件、多属性驼峰、+=/-= 相对值、toggle 预定义值与队列动画实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:6eff287fbd5d45f3f37e22a3eb7f1f7de5783bf0af1fbe8f5e5c203efa4e0247

下载本站示例源码

本地运行

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

下载jQuery 动画实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:be2dd28d20c242b9dd0c4ffe5535ff43fa1ba2a046c4a145fc08451872e88596

常见错误与边界

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

练习与解答

为什么对普通 <div> 调用 animate({left: '250px'}) 时元素可能纹丝不动?当连续调用四次 div.animate(...) 时它们是同时执行还是顺序执行?

展开参考解答

默认情况下 HTML 元素的 CSS position 为 static,left 偏移不会生效,必须先设置 position: relative/absolute/fixed;连续对同一元素调用多个 animate() 会自动进入内部 fx 动画队列,按调用顺序逐一执行。

规范与官方依据