"""Offline Playwright Chromium lab for jQuery Chapter 9 (slide)."""
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 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.slideDown = function (speed, callback) {
const ms = typeof speed === "function" ? 400 : parseSpeed(speed);
const cb = typeof speed === "function" ? speed : callback;
return this.each(function (_, el) {
el.style.display = "block";
const targetH = el.dataset.naturalHeight ? Number(el.dataset.naturalHeight) : el.scrollHeight;
el.style.overflow = "hidden";
el.style.height = "0px";
void el.offsetHeight;
el.style.transition = "height " + ms + "ms ease";
el.style.height = targetH + "px";
setTimeout(function () {
el.style.transition = "none";
el.style.overflow = "";
el.style.height = targetH + "px";
void el.offsetHeight;
el.style.transition = "";
if (typeof cb === "function") cb.call(el);
}, ms + 30);
});
};
JQ.prototype.slideUp = function (speed, callback) {
const ms = typeof speed === "function" ? 400 : parseSpeed(speed);
const cb = typeof speed === "function" ? speed : callback;
return this.each(function (_, el) {
const curH = el.getBoundingClientRect().height;
el.dataset.naturalHeight = String(curH || 100);
el.style.overflow = "hidden";
el.style.height = curH + "px";
void el.offsetHeight;
el.style.transition = "height " + ms + "ms ease";
el.style.height = "0px";
setTimeout(function () {
el.style.display = "none";
el.style.transition = "";
el.style.overflow = "";
if (typeof cb === "function") cb.call(el);
}, ms + 15);
});
};
JQ.prototype.slideToggle = function (speed, callback) {
return this.each(function (_, el) {
if (getComputedStyle(el).display === "none") $(el).slideDown(speed, callback);
else $(el).slideUp(speed, 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>
.flip, .panel {{ width: 90%; margin: 6px auto; text-align: center; background: #e5eecc; border: 1px solid #c3c3c3; box-sizing: border-box; }}
.panel {{ height: 100px; }}
.initially-hidden {{ display: none; }}
</style>
<script>{MINI_JQ}</script>
<script>
window.__slideLog = [];
$(document).ready(function () {{
$("#flip-down").click(function () {{
$("#panel-down").slideDown(80, function () {{
window.__slideLog.push("down_done:" + getComputedStyle(this).display + ":" + getComputedStyle(this).height);
}});
}});
$("#flip-up").click(function () {{
$("#panel-up").slideUp(80, function () {{
window.__slideLog.push("up_done:" + getComputedStyle(this).display);
}});
}});
$("#flip-toggle").click(function () {{
$("#panel-toggle").slideToggle(60, function () {{
window.__toggleStep = (window.__toggleStep || 0) + 1;
window.__slideLog.push("toggle:" + window.__toggleStep + ":" + getComputedStyle(this).display);
}});
}});
}});
</script>
</head>
<body>
<p id="flip-down" class="flip">点击向下滑动面板</p>
<div id="panel-down" class="panel initially-hidden" data-natural-height="100">向下滑动内容</div>
<p id="flip-up" class="flip">点击向上收起面板</p>
<div id="panel-up" class="panel" data-natural-height="100">向上收起内容</div>
<p id="flip-toggle" class="flip">点击切换滑动面板</p>
<div id="panel-toggle" class="panel initially-hidden" data-natural-height="100">往返切换内容</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: slideDown() on hidden panel
init_down = page.evaluate("() => getComputedStyle(document.getElementById('panel-down')).display")
page.locator("#flip-down").click()
page.wait_for_function("() => window.__slideLog.length === 1", timeout=3000)
act1 = page.evaluate(
"""(initDisp) => ({
initial_display: initDisp,
final_display: getComputedStyle(document.getElementById("panel-down")).display,
final_height: getComputedStyle(document.getElementById("panel-down")).height,
callback_log: window.__slideLog[0]
})""",
init_down,
)
exp1 = {
"initial_display": "none",
"final_display": "block",
"final_height": "100px",
"callback_log": "down_done:block:100px",
}
cases.append(dict(name="slidedown_hidden_panel", passed=(act1 == exp1), expected=exp1, actual=act1))
# Case 2: slideUp() on visible panel
init_up = page.evaluate(
"() => ({ display: getComputedStyle(document.getElementById('panel-up')).display, height: getComputedStyle(document.getElementById('panel-up')).height })"
)
page.locator("#flip-up").click()
page.wait_for_function("() => window.__slideLog.length === 2", timeout=3000)
act2 = page.evaluate(
"""(initUp) => ({
initial: initUp,
final_display: getComputedStyle(document.getElementById("panel-up")).display,
callback_log: window.__slideLog[1]
})""",
init_up,
)
exp2 = {
"initial": {"display": "block", "height": "100px"},
"final_display": "none",
"callback_log": "up_done:none",
}
cases.append(dict(name="slideup_visible_panel", passed=(act2 == exp2), expected=exp2, actual=act2))
# Case 3: slideToggle() two-click cycle
page.locator("#flip-toggle").click()
page.wait_for_function("() => window.__toggleStep === 1", timeout=3000)
mid_toggle = page.evaluate(
"() => ({ display: getComputedStyle(document.getElementById('panel-toggle')).display, height: getComputedStyle(document.getElementById('panel-toggle')).height })"
)
page.locator("#flip-toggle").click()
page.wait_for_function("() => window.__toggleStep === 2", timeout=3000)
end_toggle = page.evaluate("() => getComputedStyle(document.getElementById('panel-toggle')).display")
act3 = {
"after_click1": mid_toggle,
"after_click2_display": end_toggle,
"toggle_logs": page.evaluate("() => window.__slideLog.slice(2)"),
}
exp3 = {
"after_click1": {"display": "block", "height": "100px"},
"after_click2_display": "none",
"toggle_logs": ["toggle:1:block", "toggle:2:none"],
}
cases.append(dict(name="slidetoggle_roundtrip", passed=(act3 == exp3), expected=exp3, actual=act3))
# Case 4: Speed parameter parsing
act4 = page.evaluate(
"() => ({ default: $.parseSpeed(), slow: $.parseSpeed('slow'), fast: $.parseSpeed('fast'), ms500: $.parseSpeed(500) })"
)
exp4 = {"default": 400, "slow": 600, "fast": 200, "ms500": 500}
cases.append(dict(name="slide_speed_parameters", 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-slide-lab/explore-slide.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-slide.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a907.zip