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

运行 hide/show 基础切换、带速度与 linear 回调隐藏、toggle 与面板折叠实验

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

MINI_JQ = r"""
(function (global) {
  function parseSpeed(speed) {
    if (speed === undefined || speed === null) return 0;
    if (speed === "slow") return 600;
    if (speed === "fast") return 200;
    if (typeof speed === "number") return Math.max(0, speed);
    return 400;
  }
  function normalizeArgs(speed, easing, callback) {
    if (typeof speed === "function") return { ms: 0, easing: "swing", cb: speed };
    if (typeof easing === "function") return { ms: parseSpeed(speed), easing: "swing", cb: easing };
    return { ms: parseSpeed(speed), easing: easing || "swing", cb: typeof callback === "function" ? callback : null };
  }
  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.hide = function (speed, easing, callback) {
    const opt = normalizeArgs(speed, easing, callback);
    return this.each(function (_, el) {
      if (opt.ms === 0) {
        el.style.display = "none";
        if (opt.cb) opt.cb.call(el);
      } else {
        el.dataset.lastEasing = opt.easing;
        el.dataset.lastSpeed = String(opt.ms);
        el.style.transition = "opacity " + opt.ms + "ms " + (opt.easing === "linear" ? "linear" : "ease");
        el.style.opacity = "0";
        setTimeout(function () {
          el.style.display = "none";
          el.style.opacity = "";
          el.style.transition = "";
          if (opt.cb) opt.cb.call(el);
        }, opt.ms);
      }
    });
  };
  JQ.prototype.show = function (speed, easing, callback) {
    const opt = normalizeArgs(speed, easing, callback);
    return this.each(function (_, el) {
      if (opt.ms === 0) {
        el.style.display = "block";
        if (opt.cb) opt.cb.call(el);
      } else {
        el.style.display = "block";
        el.style.opacity = "0";
        void el.offsetHeight;
        el.style.transition = "opacity " + opt.ms + "ms " + (opt.easing === "linear" ? "linear" : "ease");
        el.style.opacity = "1";
        setTimeout(function () {
          el.style.transition = "";
          if (opt.cb) opt.cb.call(el);
        }, opt.ms);
      }
    });
  };
  JQ.prototype.toggle = function (speed, easing, callback) {
    return this.each(function (_, el) {
      const hidden = getComputedStyle(el).display === "none";
      if (hidden) $(el).show(speed, easing, callback);
      else $(el).hide(speed, easing, callback);
    });
  };
  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([]);
  }
  $.parseSpeed = parseSpeed;
  $.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>
    div.panel, p.flip {{ width: 90%; margin: 6px auto; padding: 5px; text-align: center; background: #e5eecc; border: 1px solid #c3c3c3; }}
    div.panel {{ height: 100px; display: none; }}
  </style>
  <script>{MINI_JQ}</script>
  <script>
    window.__cbEvents = [];
    $(document).ready(function () {{
      $("#hide").click(function () {{ $("#basic-p").hide(); }});
      $("#show").click(function () {{ $("#basic-p").show(); }});
      $(".hidebtn").click(function () {{
        $("#timed-box").hide(120, "linear", function () {{
          window.__cbEvents.push({{
            id: this.id,
            display_in_cb: getComputedStyle(this).display,
            easing: this.dataset.lastEasing
          }});
        }});
      }});
      $("#toggle-btn").click(function () {{ $("#toggle-p").toggle(); }});
      $(".flip").click(function () {{ $(".panel").toggle(); }});
    }});
  </script>
</head>
<body>
  <p id="basic-p">基础 hide/show 段落</p>
  <button id="hide" type="button">隐藏</button>
  <button id="show" type="button">显示</button>

  <div id="timed-box">带时长与回调的容器</div>
  <button class="hidebtn" type="button">延迟隐藏</button>

  <p id="toggle-p">切换可见性段落</p>
  <button id="toggle-btn" type="button">切换</button>

  <p class="flip">点击 显示/隐藏面板</p>
  <div class="panel">快捷学习内容面板</div>
</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: hide() and show() basic cycle
            d0 = page.evaluate("() => getComputedStyle(document.getElementById('basic-p')).display")
            page.locator("#hide").click()
            d1 = page.evaluate("() => getComputedStyle(document.getElementById('basic-p')).display")
            page.locator("#show").click()
            d2 = page.evaluate("() => getComputedStyle(document.getElementById('basic-p')).display")
            act1 = {"initial": d0, "after_hide": d1, "after_show": d2}
            exp1 = {"initial": "block", "after_hide": "none", "after_show": "block"}
            cases.append(dict(name="hide_and_show_basic", passed=(act1 == exp1), expected=exp1, actual=act1))

            # Case 2: hide(speed, easing, callback) + speed keyword parser
            speed_map = page.evaluate(
                "() => ({ slow: $.parseSpeed('slow'), fast: $.parseSpeed('fast'), ms1000: $.parseSpeed(1000) })"
            )
            page.locator(".hidebtn").click()
            cb_before = page.evaluate("() => window.__cbEvents.length")
            page.wait_for_function("() => window.__cbEvents.length === 1", timeout=3000)
            act2 = page.evaluate(
                """(args) => ({
                    speed_map: args.speed_map,
                    cb_count_immediately: args.cb_before,
                    final_display: getComputedStyle(document.getElementById("timed-box")).display,
                    callback_record: window.__cbEvents[0]
                })""",
                {"speed_map": speed_map, "cb_before": cb_before},
            )
            exp2 = {
                "speed_map": {"slow": 600, "fast": 200, "ms1000": 1000},
                "cb_count_immediately": 0,
                "final_display": "none",
                "callback_record": {"id": "timed-box", "display_in_cb": "none", "easing": "linear"},
            }
            cases.append(dict(name="hide_speed_easing_callback", passed=(act2 == exp2), expected=exp2, actual=act2))

            # Case 3: toggle() cycle
            t0 = page.evaluate("() => getComputedStyle(document.getElementById('toggle-p')).display")
            page.locator("#toggle-btn").click()
            t1 = page.evaluate("() => getComputedStyle(document.getElementById('toggle-p')).display")
            page.locator("#toggle-btn").click()
            t2 = page.evaluate("() => getComputedStyle(document.getElementById('toggle-p')).display")
            act3 = {"initial": t0, "click1": t1, "click2": t2}
            exp3 = {"initial": "block", "click1": "none", "click2": "block"}
            cases.append(dict(name="toggle_visibility_cycle", passed=(act3 == exp3), expected=exp3, actual=act3))

            # Case 4: Panel flip demo (.flip toggles .panel)
            p0 = page.evaluate("() => getComputedStyle(document.querySelector('.panel')).display")
            page.locator(".flip").click()
            p1 = page.evaluate(
                "() => ({ display: getComputedStyle(document.querySelector('.panel')).display, height: getComputedStyle(document.querySelector('.panel')).height })"
            )
            page.locator(".flip").click()
            p2 = page.evaluate("() => getComputedStyle(document.querySelector('.panel')).display")
            act4 = {"initial": p0, "after_click1": p1, "after_click2": p2}
            exp4 = {"initial": "none", "after_click1": {"display": "block", "height": "100px"}, "after_click2": "none"}
            cases.append(dict(name="panel_flip_toggle_demo", passed=(act4 == exp4), expected=exp4, actual=act4))
        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-hide-show-lab/explore-hide-show.py

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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