蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-animate.py
explore-animate.py315 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/jquery-animate-lab/explore-animate.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-animate.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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