"""Offline Playwright Chromium lab for jQuery Chapter 8 (fade)."""
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.fadeIn = 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";
el.style.opacity = "0";
void el.offsetHeight;
el.style.transition = "opacity " + ms + "ms ease";
el.style.opacity = "1";
setTimeout(function () {
el.style.transition = "none";
el.style.opacity = "1";
void el.offsetHeight;
el.style.transition = "";
if (typeof cb === "function") cb.call(el);
}, ms + 30);
});
};
JQ.prototype.fadeOut = 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.transition = "opacity " + ms + "ms ease";
el.style.opacity = "0";
setTimeout(function () {
el.style.display = "none";
el.style.transition = "";
if (typeof cb === "function") cb.call(el);
}, ms + 15);
});
};
JQ.prototype.fadeToggle = function (speed, callback) {
return this.each(function (_, el) {
if (getComputedStyle(el).display === "none") $(el).fadeIn(speed, callback);
else $(el).fadeOut(speed, callback);
});
};
JQ.prototype.fadeTo = function (speed, opacity, callback) {
const ms = parseSpeed(speed);
return this.each(function (_, el) {
if (getComputedStyle(el).display === "none") el.style.display = "block";
el.style.transition = "opacity " + ms + "ms ease";
el.style.opacity = String(opacity);
setTimeout(function () {
el.style.transition = "none";
el.style.opacity = String(opacity);
void el.offsetHeight;
el.style.transition = "";
if (typeof callback === "function") callback.call(el);
}, ms + 30);
});
};
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>
.box {{ width: 80px; height: 80px; margin: 4px; background: #2563eb; }}
.hidden-box {{ display: none; }}
</style>
<script>{MINI_JQ}</script>
<script>
window.__done = [];
$(document).ready(function () {{
$("#btn-in").click(function () {{
window.__done = [];
$("#in1").fadeIn(40, function () {{ window.__done.push("in1"); }});
$("#in2").fadeIn(100, function () {{ window.__done.push("in2"); }});
$("#in3").fadeIn(180, function () {{ window.__done.push("in3"); }});
}});
$("#btn-out").click(function () {{
window.__done = [];
$("#out1").fadeOut(40, function () {{ window.__done.push("out1"); }});
$("#out2").fadeOut(100, function () {{ window.__done.push("out2"); }});
$("#out3").fadeOut(180, function () {{ window.__done.push("out3"); }});
}});
$("#btn-toggle").click(function () {{
$("#tog1").fadeToggle(50, function () {{
window.__toggleDone = (window.__toggleDone || 0) + 1;
}});
}});
$("#btn-to").click(function () {{
window.__toDone = 0;
$("#to1").fadeTo(60, 0.15, function () {{ window.__toDone += 1; }});
$("#to2").fadeTo(60, 0.4, function () {{ window.__toDone += 1; }});
$("#to3").fadeTo(60, 0.7, function () {{ window.__toDone += 1; }});
}});
}});
</script>
</head>
<body>
<div id="in1" class="box hidden-box"></div>
<div id="in2" class="box hidden-box"></div>
<div id="in3" class="box hidden-box"></div>
<button id="btn-in" type="button">fadeIn</button>
<div id="out1" class="box"></div>
<div id="out2" class="box"></div>
<div id="out3" class="box"></div>
<button id="btn-out" type="button">fadeOut</button>
<div id="tog1" class="box hidden-box"></div>
<button id="btn-toggle" type="button">fadeToggle</button>
<div id="to1" class="box"></div>
<div id="to2" class="box"></div>
<div id="to3" class="box"></div>
<button id="btn-to" type="button">fadeTo</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: fadeIn() with staggered durations + standard speed mapping
speed_map = page.evaluate(
"() => ({ default: $.parseSpeed(), slow: $.parseSpeed('slow'), fast: $.parseSpeed('fast'), ms3000: $.parseSpeed(3000) })"
)
page.locator("#btn-in").click()
page.wait_for_function("() => window.__done.length === 3", timeout=3000)
act1 = page.evaluate(
"""(sm) => ({
speed_map: sm,
order: window.__done.slice(),
displays: ["in1", "in2", "in3"].map(id => getComputedStyle(document.getElementById(id)).display),
opacities: ["in1", "in2", "in3"].map(id => Number(getComputedStyle(document.getElementById(id)).opacity))
})""",
speed_map,
)
exp1 = {
"speed_map": {"default": 400, "slow": 600, "fast": 200, "ms3000": 3000},
"order": ["in1", "in2", "in3"],
"displays": ["block", "block", "block"],
"opacities": [1, 1, 1],
}
cases.append(dict(name="fadein_staggered_speeds", passed=(act1 == exp1), expected=exp1, actual=act1))
# Case 2: fadeOut() hides elements after opacity transition
page.locator("#btn-out").click()
page.wait_for_function("() => window.__done.length === 3", timeout=3000)
act2 = page.evaluate(
"""() => ({
order: window.__done.slice(),
displays: ["out1", "out2", "out3"].map(id => getComputedStyle(document.getElementById(id)).display)
})"""
)
exp2 = {"order": ["out1", "out2", "out3"], "displays": ["none", "none", "none"]}
cases.append(dict(name="fadeout_staggered_speeds", passed=(act2 == exp2), expected=exp2, actual=act2))
# Case 3: fadeToggle() roundtrip none -> block -> none
page.locator("#btn-toggle").click()
page.wait_for_function("() => window.__toggleDone === 1", timeout=3000)
mid_state = page.evaluate(
"() => ({ display: getComputedStyle(document.getElementById('tog1')).display, opacity: Number(getComputedStyle(document.getElementById('tog1')).opacity) })"
)
page.locator("#btn-toggle").click()
page.wait_for_function("() => window.__toggleDone === 2", timeout=3000)
end_disp = page.evaluate("() => getComputedStyle(document.getElementById('tog1')).display")
act3 = {"after_click1": mid_state, "after_click2_display": end_disp}
exp3 = {"after_click1": {"display": "block", "opacity": 1}, "after_click2_display": "none"}
cases.append(dict(name="fadetoggle_roundtrip", passed=(act3 == exp3), expected=exp3, actual=act3))
# Case 4: fadeTo() to 0.15, 0.4, 0.7 keeping display: block
page.locator("#btn-to").click()
page.wait_for_function("() => window.__toDone === 3", timeout=3000)
act4 = page.evaluate(
"""() => ({
displays: ["to1", "to2", "to3"].map(id => getComputedStyle(document.getElementById(id)).display),
opacities: ["to1", "to2", "to3"].map(id => Number(Number(getComputedStyle(document.getElementById(id)).opacity).toFixed(2)))
})"""
)
exp4 = {"displays": ["block", "block", "block"], "opacities": [0.15, 0.4, 0.7]}
cases.append(dict(name="fadeto_target_opacities", 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-fade-lab/explore-fade.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-fade.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a892.zip