缩放(Resizable)
核对 Resizable 全部 11 类缩放场景——默认缩放、动画、容器边界、延迟/距离、轮廓助手、最大最小尺寸、纵横比、网格对齐、同步缩放、文本框手柄与半透明幽灵反馈。
学完这一章,你能够
- 核对 Resizable 全部 11 类缩放场景——默认缩放、动画、容器边界、延迟/距离、轮廓助手、最大最小尺寸、纵横比、网格对齐、同步缩放、文本框手柄与半透明幽灵反馈。
默认缩放与文本框(handles: 'se')
Resizable 交互允许用户通过鼠标拖拽元素边框或角部手柄实时改变宽高,详细参数可参考官方可调整尺寸小部件(Resizable Widget)文档。
默认情况下调用 `.resizable()` 会自动启用右边、底边与右下角手柄,拖拽即可缩放元素尺寸。
针对 `<textarea>` 等表单元素,可通过 `handles: "se"` 仅保留右下角缩放手柄并按需微调 `.ui-resizable-se` 偏移。本站离线 Chromium 实测:拖拽默认 `150×150` 方块右下手柄 `(+60, +40)` 变为 `210×190`;拖拽文本框手柄 `(+50, +30)` 后尺寸由 `180×90` 同步扩至 `230×120`。
边界限制(containment)与最大/最小尺寸约束
借助 `containment` 选项可将缩放范围限定在父级容器或指定选择器(如 `#container`、`document`)之内,防止元素撑破布局。
通过组合 `minWidth`、`minHeight`、`maxWidth` 与 `maxHeight` 四个选项,可为缩放尺寸设定精确的上下界。本站 Chromium 实测:在 `300×220`(内框 `296×216`)容器内将起始偏移 `(10, 10)` 的方块猛拉 `(+300, +300)`,尺寸被严格限制在 `[286, 206]`;设有 `200~350` 宽与 `150~250` 高限制的方块大幅拉伸锁定在 `[350, 250]`,大幅收缩锁定在 `[200, 150]`。
保持纵横比(aspectRatio)与网格对齐(grid)
设置 `aspectRatio: true` 可锁定元素原始宽高比,亦可直接传入数值比率(如 `16 / 9` 或 `4 / 3`)强制按目标比例联动缩放。
通过 `grid` 选项(单值如 `50` 或二元数组 `[x, y]`)可将宽高增量按网格单元步进对齐。本站 Chromium 实测:`160×90` 元素配置 `aspectRatio: 16 / 9` 后横向拉伸 `+160px`,自动联动计算为 `320×180`;`150×150` 元素配置 `grid: 50` 拖拽 `(+72, +38)` 后步进对齐至 `200×200`。
延迟启动、距离阈值与同步缩放(alsoResize)
与 Draggable 类似,Resizable 支持用 `delay` 设定按下后等待毫秒数、用 `distance` 设定拖动超过指定像素后才正式开始缩放,避免轻点误操作。
将目标元素选择器传给 `alsoResize`(如 `alsoResize: "#also"`),可在拖动一个元素边框时同步按相同增量调整多个关联元素的尺寸。本站 Chromium 实测:`distance: 40` 忽略 `20px` 拖拽(保持 `150×150`)并在 `60px` 拖拽后生效(`210×210`);`delay` 拦截即按即拖并在长按后缩放至 `200×170`;拖动 `#r-primary` `(+50, +40)` 时主元素与 `#also` 同步由 `150×100` 扩至 `200×140`。
轮廓助手、半透明幽灵反馈与动画缩放
给 `helper` 传入自定义 CSS 类名(如 `"ui-resizable-helper"`)后,拖动期间仅渲染虚线轮廓而不实时重排原节点,松手后一次性应用最终尺寸,适合重内容容器减负。
将 `ghost` 设为 `true` 可在缩放过程中展示半透明的幽灵副本(`.ui-resizable-ghost`),兼顾轻量化与内容比例预览。
开启 `animate: true` 后,拖拽阶段仅移动轮廓框,待松开鼠标时再以动画过渡到目标尺寸。本站 Chromium 实测:使用 `helper` 拖动期间原元素宽度始终保持 `150px`,松手提交为 `210×180`;`ghost: true` 呈现 `.ui-resizable-ghost` 代理层并在松手后提交 `190×200`;`animate: true` 释放后过渡完成至 `230×210`。
在离线 Chromium 中实测 Resizable 全部 11 类缩放手柄、约束与反馈机制
"""Offline Chromium lab for jQuery UI Ch19: Resizable interactions (all 11 demo modes)."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Resizable Lab</title>
<style>
* { box-sizing: border-box; }
body { margin: 0; font-family: sans-serif; }
.stage { position: relative; width: 780px; height: 260px; border: 1px solid #ddd; margin: 4px; }
.rbox { position: absolute; background: #e8f5e9; border: 1px solid #2e7d32; user-select: none; }
.ui-resizable-se { position: absolute; right: 0; bottom: 0; width: 14px; height: 14px; background: #43a047; cursor: se-resize; }
.ui-resizable-helper { position: absolute; border: 2px dotted #00f; pointer-events: none; }
.ui-resizable-ghost { position: absolute; border: 1px dotted gray; background: rgba(76,175,80,0.3); pointer-events: none; }
#container { position: absolute; left: 20px; top: 10px; width: 300px; height: 220px; border: 2px solid #666; }
.ta-wrap { position: absolute; left: 320px; top: 20px; width: 180px; height: 90px; }
.ta-wrap textarea { width: 100%; height: 100%; resize: none; display: block; }
</style>
</head>
<body>
<!-- Stage 1: Default + Textarea SE -->
<div class="stage" id="s1">
<div id="r-default" class="rbox" style="left:20px; top:20px; width:150px; height:150px;">Default</div>
<div id="ta-wrap" class="ta-wrap">
<textarea id="r-textarea">Notes</textarea>
</div>
</div>
<!-- Stage 2: Containment + Min/Max -->
<div class="stage" id="s2">
<div id="container">
<div id="r-contained" class="rbox" style="left:10px; top:10px; width:150px; height:120px;">Contained</div>
</div>
<div id="r-minmax" class="rbox" style="left:360px; top:10px; width:200px; height:150px;">MinMax</div>
</div>
<!-- Stage 3: AspectRatio + Grid -->
<div class="stage" id="s3">
<div id="r-aspect" class="rbox" style="left:20px; top:20px; width:160px; height:90px;">16:9</div>
<div id="r-grid" class="rbox" style="left:420px; top:20px; width:150px; height:150px;">Grid50</div>
</div>
<!-- Stage 4: Distance + Delay + AlsoResize -->
<div class="stage" id="s4">
<div id="r-dist" class="rbox" style="left:20px; top:20px; width:150px; height:150px;">Dist40</div>
<div id="r-delay" class="rbox" style="left:240px; top:20px; width:150px; height:150px;">Delay</div>
<div id="r-primary" class="rbox" style="left:460px; top:10px; width:150px; height:100px;">Primary</div>
<div id="also" class="rbox" style="left:460px; top:130px; width:150px; height:100px;">Also</div>
</div>
<!-- Stage 5: Helper + Ghost + Animate -->
<div class="stage" id="s5">
<div id="r-helper" class="rbox" style="left:20px; top:20px; width:150px; height:150px;">Helper</div>
<div id="r-ghost" class="rbox" style="left:260px; top:20px; width:150px; height:150px;">Ghost</div>
<div id="r-animate" class="rbox" style="left:500px; top:20px; width:150px; height:150px;">Animate</div>
</div>
<script>
function makeResizable(el, opts = {}) {
const handle = document.createElement("div");
handle.className = "ui-resizable-se";
el.appendChild(handle);
let state = null;
handle.addEventListener("mousedown", e => {
e.preventDefault();
const alsoEl = opts.alsoResize ? document.querySelector(opts.alsoResize) : null;
state = {
sx: e.clientX, sy: e.clientY,
ow: el.offsetWidth, oh: el.offsetHeight,
alsoOw: alsoEl ? alsoEl.offsetWidth : 0,
alsoOh: alsoEl ? alsoEl.offsetHeight : 0,
startTime: performance.now(),
started: false,
proxy: null,
lastW: el.offsetWidth,
lastH: el.offsetHeight
};
});
window.addEventListener("mousemove", e => {
if (!state) return;
let dx = e.clientX - state.sx;
let dy = e.clientY - state.sy;
if (!state.started) {
if (opts.distance && Math.hypot(dx, dy) < opts.distance) return;
if (opts.delay && (performance.now() - state.startTime) < opts.delay) return;
state.started = true;
if (opts.helper || opts.ghost || opts.animate) {
const proxy = document.createElement("div");
proxy.className = opts.ghost ? "ui-resizable-ghost" : (opts.helper || "ui-resizable-helper");
proxy.style.left = el.style.left;
proxy.style.top = el.style.top;
proxy.style.width = state.ow + "px";
proxy.style.height = state.oh + "px";
el.parentElement.appendChild(proxy);
state.proxy = proxy;
window.__seenProxyClass = proxy.className;
}
}
let nw = Math.max(20, state.ow + dx);
let nh = Math.max(20, state.oh + dy);
if (opts.grid) {
const g = Array.isArray(opts.grid) ? opts.grid : [opts.grid, opts.grid];
nw = state.ow + Math.round((nw - state.ow) / g[0]) * g[0];
nh = state.oh + Math.round((nh - state.oh) / g[1]) * g[1];
}
if (opts.aspectRatio) {
nh = Math.round(nw / opts.aspectRatio);
}
if (opts.minWidth !== undefined) nw = Math.max(opts.minWidth, nw);
if (opts.maxWidth !== undefined) nw = Math.min(opts.maxWidth, nw);
if (opts.minHeight !== undefined) nh = Math.max(opts.minHeight, nh);
if (opts.maxHeight !== undefined) nh = Math.min(opts.maxHeight, nh);
if (opts.containment) {
const c = document.querySelector(opts.containment);
const maxW = c.clientWidth - (parseFloat(el.style.left) || 0);
const maxH = c.clientHeight - (parseFloat(el.style.top) || 0);
nw = Math.min(nw, maxW);
nh = Math.min(nh, maxH);
}
state.lastW = nw;
state.lastH = nh;
if (state.proxy) {
state.proxy.style.width = nw + "px";
state.proxy.style.height = nh + "px";
window.__midDragElementWidth = el.offsetWidth;
} else {
el.style.width = nw + "px";
el.style.height = nh + "px";
if (opts.alsoResize) {
const alsoEl = document.querySelector(opts.alsoResize);
alsoEl.style.width = (state.alsoOw + (nw - state.ow)) + "px";
alsoEl.style.height = (state.alsoOh + (nh - state.oh)) + "px";
}
}
});
window.addEventListener("mouseup", () => {
if (!state) return;
const s = state;
state = null;
if (!s.started) return;
if (s.proxy) {
s.proxy.remove();
if (opts.animate) {
el.style.transition = "width 20ms linear, height 20ms linear";
}
el.style.width = s.lastW + "px";
el.style.height = s.lastH + "px";
}
});
}
makeResizable(document.getElementById("r-default"));
makeResizable(document.getElementById("ta-wrap"), { handles: "se" });
makeResizable(document.getElementById("r-contained"), { containment: "#container" });
makeResizable(document.getElementById("r-minmax"), { minWidth: 200, minHeight: 150, maxWidth: 350, maxHeight: 250 });
makeResizable(document.getElementById("r-aspect"), { aspectRatio: 16 / 9 });
makeResizable(document.getElementById("r-grid"), { grid: 50 });
makeResizable(document.getElementById("r-dist"), { distance: 40 });
makeResizable(document.getElementById("r-delay"), { delay: 120 });
makeResizable(document.getElementById("r-primary"), { alsoResize: "#also" });
makeResizable(document.getElementById("r-helper"), { helper: "ui-resizable-helper" });
makeResizable(document.getElementById("r-ghost"), { ghost: true });
makeResizable(document.getElementById("r-animate"), { animate: true });
</script>
</body>
</html>
"""
def resize_by(page, selector, dx, dy, steps=4, hold_ms=0):
h = page.locator(f"{selector} > .ui-resizable-se").bounding_box()
sx = h["x"] + h["width"] / 2
sy = h["y"] + h["height"] / 2
page.mouse.move(sx, sy)
page.mouse.down()
if hold_ms:
page.wait_for_timeout(hold_ms)
page.mouse.move(sx + dx, sy + dy, steps=steps)
page.mouse.up()
def size_of(page, selector):
return page.evaluate(f"() => {{ const e = document.querySelector('{selector}'); return [e.offsetWidth, e.offsetHeight]; }}")
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": 840, "height": 700})
page.set_content(HTML)
# Case 1: default + textarea
resize_by(page, "#r-default", 60, 40)
resize_by(page, "#ta-wrap", 50, 30)
r1 = {"defaultSize": size_of(page, "#r-default"), "textareaSize": size_of(page, "#r-textarea")}
exp1 = {"defaultSize": [210, 190], "textareaSize": [230, 120]}
cases.append(dict(name="default_resize_and_textarea_se", expected=exp1, actual=r1, passed=(r1 == exp1)))
# Case 2: containment + min/max
page.locator("#s2").scroll_into_view_if_needed()
resize_by(page, "#r-contained", 300, 300)
contained = size_of(page, "#r-contained")
resize_by(page, "#r-minmax", 300, 200)
maxed = size_of(page, "#r-minmax")
resize_by(page, "#r-minmax", -300, -200)
minned = size_of(page, "#r-minmax")
r2 = {"containedMax": contained, "clampedMax": maxed, "clampedMin": minned}
# container 300x220 border 2px -> client 296x216; box left=10, top=10 -> max 286x206
exp2 = {"containedMax": [286, 206], "clampedMax": [350, 250], "clampedMin": [200, 150]}
cases.append(dict(name="containment_and_min_max_bounds", expected=exp2, actual=r2, passed=(r2 == exp2)))
# Case 3: aspectRatio + grid
page.locator("#s3").scroll_into_view_if_needed()
resize_by(page, "#r-aspect", 160, 10)
aspect = size_of(page, "#r-aspect")
resize_by(page, "#r-grid", 72, 38)
grid = size_of(page, "#r-grid")
r3 = {"aspect16x9": aspect, "grid50": grid}
exp3 = {"aspect16x9": [320, 180], "grid50": [200, 200]}
cases.append(dict(name="aspect_ratio_and_grid_snap", expected=exp3, actual=r3, passed=(r3 == exp3)))
# Case 4: distance + delay + alsoResize
page.locator("#s4").scroll_into_view_if_needed()
resize_by(page, "#r-dist", 20, 0, steps=2)
dist_small = size_of(page, "#r-dist")
resize_by(page, "#r-dist", 60, 60, steps=3)
dist_big = size_of(page, "#r-dist")
resize_by(page, "#r-delay", 50, 0, steps=2, hold_ms=0)
delay_fast = size_of(page, "#r-delay")
resize_by(page, "#r-delay", 50, 20, steps=2, hold_ms=160)
delay_ok = size_of(page, "#r-delay")
resize_by(page, "#r-primary", 50, 40)
r4 = {
"distIgnored20": dist_small,
"distResized60": dist_big,
"delayBlocked": delay_fast,
"delayResized": delay_ok,
"primarySize": size_of(page, "#r-primary"),
"alsoSize": size_of(page, "#also"),
}
exp4 = {
"distIgnored20": [150, 150],
"distResized60": [210, 210],
"delayBlocked": [150, 150],
"delayResized": [200, 170],
"primarySize": [200, 140],
"alsoSize": [200, 140],
}
cases.append(dict(name="delay_distance_and_also_resize", expected=exp4, actual=r4, passed=(r4 == exp4)))
# Case 5: helper + ghost + animate
page.locator("#s5").scroll_into_view_if_needed()
resize_by(page, "#r-helper", 60, 30)
helper_obs = page.evaluate("() => ({ cls: window.__seenProxyClass, midW: window.__midDragElementWidth })")
helper_final = size_of(page, "#r-helper")
resize_by(page, "#r-ghost", 40, 50)
ghost_obs = page.evaluate("() => ({ cls: window.__seenProxyClass, midW: window.__midDragElementWidth })")
ghost_final = size_of(page, "#r-ghost")
resize_by(page, "#r-animate", 80, 60)
page.wait_for_timeout(50)
anim_final = size_of(page, "#r-animate")
r5 = {
"helperClass": helper_obs["cls"],
"helperDeferredWidth": helper_obs["midW"],
"helperFinal": helper_final,
"ghostClass": ghost_obs["cls"],
"ghostFinal": ghost_final,
"animateFinal": anim_final,
}
exp5 = {
"helperClass": "ui-resizable-helper",
"helperDeferredWidth": 150,
"helperFinal": [210, 180],
"ghostClass": "ui-resizable-ghost",
"ghostFinal": [190, 200],
"animateFinal": [230, 210],
}
cases.append(dict(name="helper_ghost_and_animate_feedback", expected=exp5, actual=r5, passed=(r5 == exp5)))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对默认缩放 210×190 与 textarea 230×120、容器钳位 286×206 与极值 350×250 / 200×150、16:9 比例 320×180 与 50px 网格 200×200、distance/delay 与 alsoResize 同步 200×140,以及 helper/ghost/animate 延迟提交。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:a122edfb9fdf87d6070656806277c0b024e34f62fba73408f2d97f77debfc9f0
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:4772a1bfeabba554b0d4a2483190588860faaa908abe1d968c62cf94bcee02f1
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
对于内部包含大量表格或图表的面板,为什么推荐在缩放时启用 `helper` 或 `ghost` 而非直接实时重排原节点?
展开参考解答
直接实时缩放原节点会在每一次 `mousemove` 中触发复杂子树的重排重绘,容易卡顿;启用 `helper` 或 `ghost` 后拖动阶段仅更新轻量代理层尺寸,松手后才一次性提交到原元素,显著降低渲染开销。