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

运行点击/双击、鼠标四阶段、hover 双回调与 focus/blur 离线交互实验

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

MINI_JQ = r"""
(function (global) {
  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;
  };
  ["click", "dblclick", "mouseenter", "mouseleave", "mousedown", "mouseup", "focus", "blur"].forEach(function (evName) {
    JQ.prototype[evName] = function (fn) {
      return this.each(function (_, el) {
        if (typeof fn === "function") {
          el.addEventListener(evName, function (ev) { fn.call(el, ev); });
        } else {
          if (evName === "focus" || evName === "blur" || evName === "click") {
            el[evName]();
          } else {
            el.dispatchEvent(new MouseEvent(evName, { bubbles: evName !== "mouseenter" && evName !== "mouseleave" }));
          }
        }
      });
    };
  });
  JQ.prototype.hover = function (fnEnter, fnLeave) {
    return this.mouseenter(fnEnter).mouseleave(fnLeave || fnEnter);
  };
  JQ.prototype.hide = function () {
    return this.each(function (_, el) { el.style.display = "none"; });
  };
  JQ.prototype.css = function (prop, val) {
    const camel = prop.replace(/-([a-z])/g, function (_, c) { return c.toUpperCase(); });
    if (val === undefined) return this.elements[0] ? getComputedStyle(this.elements[0])[camel] : undefined;
    return this.each(function (_, el) { el.style[camel] = val; });
  };
  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>
    body {{ margin: 20px; font-family: sans-serif; }}
    #p1, #hover-box {{ width: 200px; height: 48px; line-height: 48px; margin: 12px 0; background: rgb(241, 245, 249); }}
    input {{ width: 200px; height: 32px; background-color: rgb(255, 255, 255); }}
  </style>
  <script>{MINI_JQ}</script>
  <script>
    window.__log = [];
    $(document).ready(function () {{
      window.__log.push("ready");
      $("#click-p").click(function () {{
        window.__log.push("click");
        $(this).hide();
      }});
      $("#prog-p").click(function () {{
        window.__log.push("prog_click");
      }});
      $("#dbl-p").dblclick(function () {{
        window.__log.push("dblclick");
        $(this).hide();
      }});
      $("#p1").mouseenter(function () {{ window.__log.push("mouseenter"); }});
      $("#p1").mouseleave(function () {{ window.__log.push("mouseleave"); }});
      $("#p1").mousedown(function () {{ window.__log.push("mousedown"); }});
      $("#p1").mouseup(function () {{ window.__log.push("mouseup"); }});
      $("#hover-box").hover(
        function () {{
          window.__log.push("hover_enter");
          $(this).css("background-color", "#d1fae5");
        }},
        function () {{
          window.__log.push("hover_leave");
          $(this).css("background-color", "#f1f5f9");
        }}
      );
      $("#name-input").focus(function () {{
        window.__log.push("focus");
        $(this).css("background-color", "#cccccc");
      }});
      $("#name-input").blur(function () {{
        window.__log.push("blur");
        $(this).css("background-color", "#ffffff");
      }});
    }});
  </script>
</head>
<body>
  <p id="click-p">单击隐藏段落</p>
  <p id="prog-p">程序触发点击段落</p>
  <p id="dbl-p">双击隐藏段落</p>
  <div id="p1">鼠标生命周期测试区</div>
  <div id="hover-box">悬停切换区域</div>
  <input id="name-input" type="text" value="alice">
  <button id="outside-btn" 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: click(), no-arg click() trigger, and dblclick()
            page.locator("#click-p").click()
            page.evaluate("() => $('#prog-p').click()")
            page.locator("#dbl-p").click()
            after_single_on_dbl = page.evaluate("() => getComputedStyle(document.getElementById('dbl-p')).display")
            page.locator("#dbl-p").dblclick()
            act1 = page.evaluate(
                """(singleDisp) => ({
                    click_p_display: getComputedStyle(document.getElementById("click-p")).display,
                    dbl_p_after_single: singleDisp,
                    dbl_p_after_dbl: getComputedStyle(document.getElementById("dbl-p")).display,
                    log_prefix: window.__log.slice()
                })""",
                after_single_on_dbl,
            )
            exp1 = {
                "click_p_display": "none",
                "dbl_p_after_single": "block",
                "dbl_p_after_dbl": "none",
                "log_prefix": ["ready", "click", "prog_click", "dblclick"],
            }
            cases.append(dict(name="click_dblclick_and_trigger", passed=(act1 == exp1), expected=exp1, actual=act1))

            # Case 2: mouseenter, mousedown, mouseup, mouseleave sequence on #p1
            page.evaluate("() => { window.__log = []; }")
            box = page.locator("#p1").bounding_box()
            cx, cy = box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
            page.mouse.move(1, 1)
            page.mouse.move(cx, cy)
            page.mouse.down()
            page.mouse.up()
            page.mouse.move(1, 1)
            act2 = {"mouse_sequence": page.evaluate("() => window.__log.slice()")}
            exp2 = {"mouse_sequence": ["mouseenter", "mousedown", "mouseup", "mouseleave"]}
            cases.append(dict(name="mouse_enter_down_up_leave", passed=(act2 == exp2), expected=exp2, actual=act2))

            # Case 3: hover(enterFn, leaveFn)
            page.evaluate("() => { window.__log = []; }")
            hbox = page.locator("#hover-box").bounding_box()
            hx, hy = hbox["x"] + hbox["width"] / 2, hbox["y"] + hbox["height"] / 2
            page.mouse.move(hx, hy)
            bg_in = page.evaluate("() => getComputedStyle(document.getElementById('hover-box')).backgroundColor")
            page.mouse.move(1, 1)
            bg_out = page.evaluate("() => getComputedStyle(document.getElementById('hover-box')).backgroundColor")
            act3 = {
                "bg_enter": bg_in,
                "bg_leave": bg_out,
                "hover_events": page.evaluate("() => window.__log.slice()"),
            }
            exp3 = {
                "bg_enter": "rgb(209, 250, 229)",
                "bg_leave": "rgb(241, 245, 249)",
                "hover_events": ["hover_enter", "hover_leave"],
            }
            cases.append(dict(name="hover_dual_handler", passed=(act3 == exp3), expected=exp3, actual=act3))

            # Case 4: focus() and blur() background color switching
            page.evaluate("() => { window.__log = []; }")
            page.locator("#name-input").focus()
            bg_focus = page.evaluate("() => getComputedStyle(document.getElementById('name-input')).backgroundColor")
            page.locator("#outside-btn").click()
            bg_blur = page.evaluate("() => getComputedStyle(document.getElementById('name-input')).backgroundColor")
            act4 = {
                "bg_focus": bg_focus,
                "bg_blur": bg_blur,
                "focus_events": page.evaluate("() => window.__log.slice()"),
            }
            exp4 = {
                "bg_focus": "rgb(204, 204, 204)",
                "bg_blur": "rgb(255, 255, 255)",
                "focus_events": ["focus", "blur"],
            }
            cases.append(dict(name="focus_and_blur_styles", 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-events-lab/explore-events.py

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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