定位(Position)
核对 .position() 的 my/at/of 锚点对齐计算、flip/fit/flipfit/none 碰撞检测策略、拖拽父元素联动重定位,以及三图循环画廊与窗口缩放重排。
学完这一章,你能够
- 核对 .position() 的 my/at/of 锚点对齐计算、flip/fit/flipfit/none 碰撞检测策略、拖拽父元素联动重定位,以及三图循环画廊与窗口缩放重排。
my / at / of 锚点对齐、碰撞检测与父元素联动
`.position()` 工具方法能够将一个元素相对于窗口、文档、另一个锚点元素或鼠标光标精确定位,详细选项与偏移语法见官方 `.position()` API 文档。
默认演示通过 `my`(自身锚点)、`at`(目标 `#parent` 锚点)与 `collision`(水平/垂直碰撞策略:`flip`、`fit`、`flipfit`、`none`)下拉框实时调用 `$( ".positionable" ).position(...)` 定位两个尺寸不同的透明区块(`75×75` 与 `120×40`),同时让 `#parent` 可拖拽并在 `drag` 事件中重算位置以检验碰撞边界。本站离线 Chromium 在 `800×600` 视口下实测:当 `#parent` 位于 `(160, 100)`、尺寸 `480×52` 时,`left top / left top` 对齐至 `[[160, 100], [160, 100]]`,`center center` 对齐至 `[[362.5, 88.5], [340, 106]]`,`right bottom` 对齐至 `[[565, 77], [520, 112]]`;将 `#parent` 移至右下边缘 `(720, 530, 60×40)` 并采用 `my: "left top"`、`at: "right bottom"` 触发溢出时,`none` 保持 `[780, 570]`、`fit` 钳位于视口内 `[725, 525]`、`flip` 与 `flipfit` 翻转至父块左上侧 `[645, 455]`;拖拽 `#parent` 位移 `[+100, +60]` 时,两被定位块同步精准跟随 `[100, 60]`。
图像循环原型与窗口缩放重定位
图像循环原型将 `left`(`my: "right middle"`、`at: "left+25 middle"`)、`center`(`center middle`)与 `right`(`my: "left middle"`、`at: "right-25 middle"`)三组 `.position()` 规则封装在 `#container` 内,并通过 `using` 回调交给动画函数平滑移动;点击“上一个/下一个”链接或左右侧图片即可循环轮换节点顺序,并在 `$( window ).resize()` 时重新居中与贴边定位。本站使用三张等尺寸离线 SVG 占位图(`earth` `458×308`、`flight` `512×307`、`rocket` `300×353`)实测:`800px` 宽容器初始 `left` 坐标依次为 `-433`(左露 `25px`)、`144`(居中)与 `775`(右露 `25px`);点击 `#next` 后 `rocket` 居中于 `250px`、`flight` 退居 `-487px`、`earth` 移至 `775px`;点击 `#previous` 还原初始序列;视口拉宽至 `1000px` 触发 `resize` 后,`flight` 重算居中至 `244px`、`rocket` 移至 `975px`。
在离线 Chromium 中实测 .position() 锚点对齐、四种碰撞策略、拖拽联动与图像循环
"""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()
- 核对 left/center/right 锚点精确坐标、none/fit/flip/flipfit 边缘处理 [780,570]/[725,525]/[645,455]、父块拖拽 [+100,+60] 同步及三图轮换与 1000px 重排。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:b92feec945a38845e6be109e2d8cf15796446929b7b55cc35d1bfcde7d0c787b
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:08f09718e7dba90d45a6feca0c51f407b0191edcbfdb032d69994c59bd608e5f
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 `.position()` 的 `collision` 选项中,`fit`、`flip` 与 `flipfit` 在元素碰到视口边界时各自如何处理?
展开参考解答
`fit` 沿碰撞轴将元素向视口内平移钳位;`flip` 将对齐方向翻转到目标元素另一侧;`flipfit` 先尝试翻转到对侧,若对侧仍超出视口再进一步执行 `fit` 钳位。