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

离线 Chromium 实测 stop() 四种参数组合与动画队列中断

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-stop.py
explore-stop.py321 行
"""Offline Playwright Chromium lab for jQuery Chapter 11 (stop)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <style>
    body { margin: 0; font-family: sans-serif; }
    #stop-btn { margin-left: 25px; }
    .flip, #panel {
      width: 300px;
      padding: 5px;
      text-align: center;
      background: #e5eecc;
      border: 1px solid #c3c3c3;
    }
    #panel {
      height: 100px;
      display: none;
      overflow: hidden;
    }
    #box {
      position: relative;
      left: 0px;
      top: 0px;
      width: 100px;
      height: 100px;
      opacity: 1;
      background: #98bf21;
    }
  </style>
</head>
<body>
  <button id="stop-btn" type="button">停止滑动</button>
  <p class="flip">点击这里,向上/向下滑动面板</p>
  <div id="panel">面板内容区域</div>
  <div id="box">动画方块</div>
  <script>
    (function () {
      const queues = new WeakMap();
      const activeTimers = new Set();

      function getQueue(el) {
        if (!queues.has(el)) queues.set(el, { active: null, pending: [] });
        return queues.get(el);
      }

      function readNumericProp(el, prop) {
        const cs = getComputedStyle(el);
        if (prop === 'opacity') return parseFloat(cs.opacity) || 0;
        const val = parseFloat(cs[prop]);
        return Number.isNaN(val) ? 0 : val;
      }

      function writeProp(el, prop, value) {
        if (prop === 'opacity') {
          el.style.opacity = String(Number(value.toFixed(4)));
        } else {
          el.style[prop] = Number(value.toFixed(2)) + 'px';
        }
      }

      function startNext(el) {
        const q = getQueue(el);
        if (q.active || q.pending.length === 0) return;
        const job = q.pending.shift();
        if (job.onStart) job.onStart();
        const startVals = {};
        for (const k of Object.keys(job.targets)) {
          startVals[k] = readNumericProp(el, k);
        }
        q.active = {
          el,
          duration: job.duration,
          elapsed: 0,
          startVals,
          targets: job.targets,
          onDone: job.onDone,
        };
        activeTimers.add(q.active);
      }

      function applyProgress(anim, ratio) {
        const clamped = Math.max(0, Math.min(1, ratio));
        for (const [k, endVal] of Object.entries(anim.targets)) {
          const cur = anim.startVals[k] + (endVal - anim.startVals[k]) * clamped;
          writeProp(anim.el, k, cur);
        }
      }

      window.__advance = function (ms) {
        const snapshot = Array.from(activeTimers);
        for (const anim of snapshot) {
          if (!activeTimers.has(anim)) continue;
          anim.elapsed += ms;
          if (anim.elapsed >= anim.duration) {
            applyProgress(anim, 1);
            activeTimers.delete(anim);
            const q = getQueue(anim.el);
            if (q.active === anim) q.active = null;
            if (anim.onDone) anim.onDone();
            startNext(anim.el);
          } else {
            applyProgress(anim, anim.elapsed / anim.duration);
          }
        }
      };

      function JQ(els) {
        this.els = Array.from(els);
        this.length = this.els.length;
      }

      JQ.prototype.click = function (fn) {
        this.els.forEach((el) => el.addEventListener('click', fn));
        return this;
      };

      JQ.prototype.slideToggle = function (duration) {
        const dur = typeof duration === 'number' ? duration : 400;
        this.els.forEach((el) => {
          const q = getQueue(el);
          const isHidden = getComputedStyle(el).display === 'none';
          if (isHidden) {
            q.pending.push({
              duration: dur,
              targets: { height: 100 },
              onStart: () => {
                el.style.display = 'block';
                el.style.height = '0px';
              },
            });
          } else {
            q.pending.push({
              duration: dur,
              targets: { height: 0 },
              onDone: () => {
                el.style.display = 'none';
              },
            });
          }
          startNext(el);
        });
        return this;
      };

      JQ.prototype.fadeTo = function (duration, opacity) {
        const dur = typeof duration === 'number' ? duration : 400;
        this.els.forEach((el) => {
          const q = getQueue(el);
          q.pending.push({ duration: dur, targets: { opacity } });
          startNext(el);
        });
        return this;
      };

      JQ.prototype.animate = function (props, duration) {
        const dur = typeof duration === 'number' ? duration : 400;
        const targets = {};
        for (const [k, v] of Object.entries(props)) {
          targets[k] = typeof v === 'string' ? parseFloat(v) : v;
        }
        this.els.forEach((el) => {
          const q = getQueue(el);
          q.pending.push({ duration: dur, targets });
          startNext(el);
        });
        return this;
      };

      JQ.prototype.stop = function (stopAll, goToEnd) {
        const clearQueue = Boolean(stopAll);
        const jumpEnd = Boolean(goToEnd);
        this.els.forEach((el) => {
          const q = getQueue(el);
          const cur = q.active;
          if (clearQueue) {
            q.pending.length = 0;
          }
          if (cur) {
            activeTimers.delete(cur);
            q.active = null;
            if (jumpEnd) {
              applyProgress(cur, 1);
              if (cur.onDone) cur.onDone();
            }
          }
          if (!clearQueue) {
            startNext(el);
          }
        });
        return this;
      };

      window.$ = function (sel) {
        return new JQ(document.querySelectorAll(sel));
      };

      window.__queueInfo = function (sel) {
        const el = document.querySelector(sel);
        const q = getQueue(el);
        return { active: Boolean(q.active), pending: q.pending.length };
      };

      window.__resetBox = function () {
        const el = document.querySelector('#box');
        const q = getQueue(el);
        if (q.active) activeTimers.delete(q.active);
        q.active = null;
        q.pending.length = 0;
        el.style.left = '0px';
        el.style.top = '0px';
        el.style.height = '100px';
        el.style.opacity = '1';
      };

      $('.flip').click(function () {
        $('#panel').slideToggle(1000);
      });
      $('#stop-btn').click(function () {
        $('#panel').stop();
      });
    })();
  </script>
</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 p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1000, "height": 700})
        page.set_content(HTML_DOC, wait_until="load")

        # Case 1: default stop() halts slideToggle mid-way
        page.click(".flip")
        page.evaluate("window.__advance(500)")
        mid_height = page.evaluate("getComputedStyle(document.querySelector('#panel')).height")
        page.click("#stop-btn")
        page.evaluate("window.__advance(600)")
        c1 = page.evaluate("""() => {
            const cs = getComputedStyle(document.querySelector('#panel'));
            const q = window.__queueInfo('#panel');
            return { display: cs.display, height: cs.height, active: q.active, pending: q.pending };
        }""")
        c1["mid_height"] = mid_height
        exp1 = {"mid_height": "50px", "display": "block", "height": "50px", "active": False, "pending": 0}
        cases.append(dict(name="stop_default_slide_panel", expected=exp1, actual=c1, passed=c1 == exp1))

        # Case 2: stop(false, false) halts current animation, runs queued next animation
        c2 = page.evaluate("""() => {
            window.__resetBox();
            $('#box').animate({ left: '200px' }, 1000).animate({ top: '120px' }, 1000);
            window.__advance(500);
            const midLeft = getComputedStyle(document.querySelector('#box')).left;
            $('#box').stop(false, false);
            const afterStopQ = window.__queueInfo('#box');
            window.__advance(1000);
            const cs = getComputedStyle(document.querySelector('#box'));
            return { midLeft, left: cs.left, top: cs.top, nextStarted: afterStopQ.active };
        }""")
        exp2 = {"midLeft": "100px", "left": "100px", "top": "120px", "nextStarted": True}
        cases.append(dict(name="stop_false_false_continues_queue", expected=exp2, actual=c2, passed=c2 == exp2))

        # Case 3: stop(true, false) halts current animation AND clears queue
        c3 = page.evaluate("""() => {
            window.__resetBox();
            $('#box').animate({ left: '200px' }, 1000).animate({ top: '120px' }, 1000);
            window.__advance(500);
            $('#box').stop(true, false);
            const afterStopQ = window.__queueInfo('#box');
            window.__advance(1000);
            const cs = getComputedStyle(document.querySelector('#box'));
            return { left: cs.left, top: cs.top, active: afterStopQ.active, pending: afterStopQ.pending };
        }""")
        exp3 = {"left": "100px", "top": "0px", "active": False, "pending": 0}
        cases.append(dict(name="stop_true_false_clears_queue", expected=exp3, actual=c3, passed=c3 == exp3))

        # Case 4: stop(true, true) vs stop(false, true) with fadeTo & animate
        c4 = page.evaluate("""() => {
            window.__resetBox();
            $('#box').animate({ left: '200px' }, 1000).animate({ top: '120px' }, 1000);
            window.__advance(500);
            $('#box').stop(true, true);
            window.__advance(1000);
            const cs1 = getComputedStyle(document.querySelector('#box'));
            const tt = { left: cs1.left, top: cs1.top };

            window.__resetBox();
            $('#box').fadeTo(1000, 0.2).animate({ height: '160px' }, 1000);
            window.__advance(500);
            $('#box').stop(false, true);
            window.__advance(1000);
            const cs2 = getComputedStyle(document.querySelector('#box'));
            const ft = { opacity: cs2.opacity, height: cs2.height };
            return { true_true: tt, false_true: ft };
        }""")
        exp4 = {
            "true_true": {"left": "200px", "top": "0px"},
            "false_true": {"opacity": "0.2", "height": "160px"},
        }
        cases.append(dict(name="stop_gotoend_and_fade_queue", expected=exp4, actual=c4, passed=c4 == exp4))

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


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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