"""Offline Chromium lab for jQuery UI Ch42: .position() alignment, collision & photo cycler."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Position Lab</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; font-family: sans-serif; font-size: 13px; }
#parent { position: absolute; left: 160px; top: 100px; width: 480px; height: 52px; padding: 5px; border: 1px solid #777; background: #fbca93; text-align: center; }
.positionable { position: absolute; display: block; background: #bcd5e6; opacity: 0.5; text-align: center; }
#positionable1 { width: 75px; height: 75px; }
#positionable2 { width: 120px; height: 40px; }
#controls { position: absolute; left: 10px; top: 200px; }
#container { overflow: hidden; position: relative; width: 100%; height: 400px; margin-top: 320px; border-top: 1px solid #aaa; }
#container img { position: absolute; }
</style>
</head>
<body>
<div id="parent">这是父元素的位置。</div>
<div class="positionable" id="positionable1">to position</div>
<div class="positionable" id="positionable2">to position 2</div>
<div id="controls">
<select id="my_horizontal"><option value="left">left</option><option value="center">center</option><option value="right">right</option></select>
<select id="my_vertical"><option value="top">top</option><option value="center">center</option><option value="bottom">bottom</option></select>
<select id="at_horizontal"><option value="left">left</option><option value="center">center</option><option value="right">right</option></select>
<select id="at_vertical"><option value="top">top</option><option value="center">center</option><option value="bottom">bottom</option></select>
<select id="collision_horizontal"><option value="flip">flip</option><option value="fit">fit</option><option value="flipfit">flipfit</option><option value="none">none</option></select>
<select id="collision_vertical"><option value="flip">flip</option><option value="fit">fit</option><option value="flipfit">flipfit</option><option value="none">none</option></select>
</div>
<div id="container">
<img data-name="earth" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='458' height='308'><rect width='458' height='308' fill='%2388c'/></svg>" width="458" height="308" alt="earth">
<img data-name="flight" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='512' height='307'><rect width='512' height='307' fill='%238c8'/></svg>" width="512" height="307" alt="flight">
<img data-name="rocket" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='300' height='353'><rect width='300' height='353' fill='%23c88'/></svg>" width="300" height="353" alt="rocket">
<a id="previous" href="#">上一个</a>
<a id="next" href="#">下一个</a>
</div>
<script>
function parseAxisToken(tok) {
const m = tok.match(/^(left|center|right|top|middle|bottom)([+-]\\d+)?$/);
let base = m[1];
if (base === "middle") base = "center";
const offset = m[2] ? parseFloat(m[2]) : 0;
return { base, offset };
}
function axisPoint(start, size, spec) {
if (spec.base === "left" || spec.base === "top") return start + spec.offset;
if (spec.base === "right" || spec.base === "bottom") return start + size + spec.offset;
return start + size / 2 + spec.offset;
}
function flipBase(b) {
if (b === "left") return "right";
if (b === "right") return "left";
if (b === "top") return "bottom";
if (b === "bottom") return "top";
return b;
}
function applyPosition(el, opts) {
const target = typeof opts.of === "string" ? document.querySelector(opts.of) : opts.of;
const isContainerRel = el.offsetParent && el.offsetParent !== document.body && el.offsetParent === target;
const tr = isContainerRel
? { left: 0, top: 0, width: target.clientWidth, height: target.clientHeight }
: target.getBoundingClientRect();
const ew = el.offsetWidth;
const eh = el.offsetHeight;
const [myH, myV] = opts.my.split(/\\s+/).map(parseAxisToken);
const [atH, atV] = opts.at.split(/\\s+/).map(parseAxisToken);
const colParts = (opts.collision || "flip flip").split(/\\s+/);
const colH = colParts[0];
const colV = colParts[1] || colParts[0];
const rawLeft = axisPoint(tr.left, tr.width, atH) - axisPoint(0, ew, myH);
const rawTop = axisPoint(tr.top, tr.height, atV) - axisPoint(0, eh, myV);
let left = rawLeft;
let top = rawTop;
const vw = window.innerWidth;
const vh = window.innerHeight;
if (!isContainerRel) {
if (colH === "flip" || colH === "flipfit") {
if (left < 0 || left + ew > vw) {
const fMy = { base: flipBase(myH.base), offset: -myH.offset };
const fAt = { base: flipBase(atH.base), offset: -atH.offset };
const flipped = axisPoint(tr.left, tr.width, fAt) - axisPoint(0, ew, fMy);
if (flipped >= 0 && flipped + ew <= vw || colH === "flipfit") left = flipped;
}
}
if (colH === "fit" || colH === "flipfit") {
if (left + ew > vw) left = vw - ew;
if (left < 0) left = 0;
}
if (colV === "flip" || colV === "flipfit") {
if (top < 0 || top + eh > vh) {
const fMy = { base: flipBase(myV.base), offset: -myV.offset };
const fAt = { base: flipBase(atV.base), offset: -atV.offset };
const flipped = axisPoint(tr.top, tr.height, fAt) - axisPoint(0, eh, fMy);
if (flipped >= 0 && flipped + eh <= vh || colV === "flipfit") top = flipped;
}
}
if (colV === "fit" || colV === "flipfit") {
if (top + eh > vh) top = vh - eh;
if (top < 0) top = 0;
}
}
const res = { left, top };
if (opts.using) {
opts.using.call(el, res);
} else {
el.style.left = left + "px";
el.style.top = top + "px";
}
return res;
}
function positionAll() {
const my = document.getElementById("my_horizontal").value + " " + document.getElementById("my_vertical").value;
const at = document.getElementById("at_horizontal").value + " " + document.getElementById("at_vertical").value;
const collision = document.getElementById("collision_horizontal").value + " " + document.getElementById("collision_vertical").value;
document.querySelectorAll(".positionable").forEach(el => {
applyPosition(el, { of: document.getElementById("parent"), my, at, collision });
});
}
document.querySelectorAll("#controls select").forEach(sel => sel.addEventListener("change", positionAll));
// Draggable parent calls positionAll on drag
const parentEl = document.getElementById("parent");
let dragState = null;
parentEl.addEventListener("mousedown", e => {
dragState = { sx: e.clientX, sy: e.clientY, ol: parseFloat(getComputedStyle(parentEl).left), ot: parseFloat(getComputedStyle(parentEl).top) };
});
window.addEventListener("mousemove", e => {
if (!dragState) return;
parentEl.style.left = (dragState.ol + e.clientX - dragState.sx) + "px";
parentEl.style.top = (dragState.ot + e.clientY - dragState.sy) + "px";
positionAll();
});
window.addEventListener("mouseup", () => { dragState = null; });
positionAll();
// Photo cycler
const container = document.getElementById("container");
function imgs() { return Array.from(container.querySelectorAll("img")); }
function placeLeft(img) {
applyPosition(img, { my: "right middle", at: "left+25 middle", of: "#container", collision: "none" });
}
function placeCenter(img) {
applyPosition(img, { my: "center middle", at: "center middle", of: "#container", collision: "none" });
}
function placeRight(img) {
applyPosition(img, { my: "left middle", at: "right-25 middle", of: "#container", collision: "none" });
}
function layoutCycler() {
const list = imgs();
placeLeft(list[0]);
placeCenter(list[1]);
placeRight(list[2]);
}
layoutCycler();
function nextImg(e) {
if (e) e.preventDefault();
const list = imgs();
placeCenter(list[2]);
placeLeft(list[1]);
placeRight(list[0]);
container.appendChild(list[0]);
}
function prevImg(e) {
if (e) e.preventDefault();
const list = imgs();
placeCenter(list[0]);
placeRight(list[1]);
placeLeft(list[2]);
container.insertBefore(list[2], container.firstChild);
}
document.getElementById("next").addEventListener("click", nextImg);
document.getElementById("previous").addEventListener("click", prevImg);
window.addEventListener("resize", layoutCycler);
window.positionAll = positionAll;
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page(viewport={"width": 800, "height": 600})
page.set_content(HTML)
# Case 1: my / at / of bounding-box alignment math
def read_pair():
return page.evaluate("""() => [
[parseFloat(document.getElementById('positionable1').style.left), parseFloat(document.getElementById('positionable1').style.top)],
[parseFloat(document.getElementById('positionable2').style.left), parseFloat(document.getElementById('positionable2').style.top)]
]""")
lt = read_pair()
page.select_option("#my_horizontal", "center")
page.select_option("#my_vertical", "center")
page.select_option("#at_horizontal", "center")
page.select_option("#at_vertical", "center")
cc = read_pair()
page.select_option("#my_horizontal", "right")
page.select_option("#my_vertical", "bottom")
page.select_option("#at_horizontal", "right")
page.select_option("#at_vertical", "bottom")
rb = read_pair()
r1 = {"leftTop": lt, "centerCenter": cc, "rightBottom": rb}
exp1 = {
"leftTop": [[160, 100], [160, 100]],
"centerCenter": [[362.5, 88.5], [340, 106]],
"rightBottom": [[565, 77], [520, 112]],
}
cases.append(dict(name="my_at_of_bounding_box_alignment", expected=exp1, actual=r1, passed=(r1 == exp1)))
# Case 2: Collision modes (none, fit, flip, flipfit) near viewport edges
page.evaluate("""() => {
const par = document.getElementById('parent');
par.style.left = '720px'; par.style.top = '530px'; par.style.width = '60px'; par.style.height = '40px';
}""")
page.select_option("#my_horizontal", "left")
page.select_option("#my_vertical", "top")
page.select_option("#at_horizontal", "right")
page.select_option("#at_vertical", "bottom")
col_results = {}
for mode in ("none", "fit", "flip", "flipfit"):
page.select_option("#collision_horizontal", mode)
page.select_option("#collision_vertical", mode)
col_results[mode] = page.evaluate("() => [parseFloat(document.getElementById('positionable1').style.left), parseFloat(document.getElementById('positionable1').style.top)]")
exp2 = {
"none": [780, 570],
"fit": [725, 525],
"flip": [645, 455],
"flipfit": [645, 455],
}
cases.append(dict(name="collision_flip_fit_flipfit_none", expected=exp2, actual=col_results, passed=(col_results == exp2)))
# Case 3: Dragging parent dynamically repositions attached elements
page.evaluate("""() => {
const par = document.getElementById('parent');
par.style.left = '160px'; par.style.top = '100px'; par.style.width = '480px'; par.style.height = '52px';
}""")
page.select_option("#my_horizontal", "left")
page.select_option("#my_vertical", "top")
page.select_option("#at_horizontal", "left")
page.select_option("#at_vertical", "top")
page.select_option("#collision_horizontal", "none")
page.select_option("#collision_vertical", "none")
before_drag = read_pair()
pb = page.locator("#parent").bounding_box()
page.mouse.move(pb["x"] + 300, pb["y"] + 20)
page.mouse.down()
page.mouse.move(pb["x"] + 400, pb["y"] + 80, steps=4)
page.mouse.up()
after_drag = read_pair()
r3 = {
"p1Delta": [round(after_drag[0][0] - before_drag[0][0]), round(after_drag[0][1] - before_drag[0][1])],
"p2Delta": [round(after_drag[1][0] - before_drag[1][0]), round(after_drag[1][1] - before_drag[1][1])],
}
exp3 = {"p1Delta": [100, 60], "p2Delta": [100, 60]}
cases.append(dict(name="parent_drag_reposition_live", expected=exp3, actual=r3, passed=(r3 == exp3)))
# Case 4: Photo cycler left/center/right, next/previous rotation & window resize
def cycler_state():
return page.evaluate("""() => Array.from(document.querySelectorAll('#container img')).map(img => ({
name: img.dataset.name,
left: Math.round(parseFloat(img.style.left))
}))""")
init_cyc = cycler_state()
page.locator("#next").click()
after_next = cycler_state()
page.locator("#previous").click()
after_prev = cycler_state()
page.set_viewport_size({"width": 1000, "height": 600})
page.wait_for_timeout(40)
after_resize = cycler_state()
r4 = {
"initial": init_cyc,
"afterNext": after_next,
"afterPrev": after_prev,
"afterResize1000": after_resize,
}
exp4 = {
"initial": [{"name": "earth", "left": -433}, {"name": "flight", "left": 144}, {"name": "rocket", "left": 775}],
"afterNext": [{"name": "flight", "left": -487}, {"name": "rocket", "left": 250}, {"name": "earth", "left": 775}],
"afterPrev": [{"name": "earth", "left": -433}, {"name": "flight", "left": 144}, {"name": "rocket", "left": 775}],
"afterResize1000": [{"name": "earth", "left": -433}, {"name": "flight", "left": 244}, {"name": "rocket", "left": 975}],
}
cases.append(dict(name="photo_cycler_left_center_right_and_resize", expected=exp4, actual=r4, passed=(r4 == exp4)))
finally:
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/jqueryui-example-position-lab/explore-example-position.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-example-position.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a931.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip