"""Offline Playwright Chromium lab for jQuery UI Ch 29: Slider."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Slider Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; }
.ui-slider { position: relative; background: #eee; border: 1px solid #aaa; margin: 10px 0; }
.ui-slider-horizontal { width: 300px; height: 12px; }
.ui-slider-vertical { width: 12px; height: 200px; }
.ui-slider-range { position: absolute; background: #4da3ff; }
.ui-slider-handle { position: absolute; width: 14px; height: 14px; background: #fff; border: 1px solid #333; }
#swatch { width: 120px; height: 60px; border: 1px solid #999; }
</style>
</head>
<body>
<div id="s-default" class="ui-slider ui-slider-horizontal" tabindex="0"></div>
<div id="s-step" class="ui-slider ui-slider-horizontal" tabindex="0"></div>
<input id="step-amount">
<div id="swatch"></div>
<div id="s-range" class="ui-slider ui-slider-horizontal"></div>
<div id="s-rmax" class="ui-slider ui-slider-horizontal"></div>
<div id="s-rmin" class="ui-slider ui-slider-horizontal"></div>
<select id="minbeds">
<option>1</option><option>2</option><option>3</option>
<option>4</option><option>5</option><option>6</option>
</select>
<div id="s-vert" class="ui-slider ui-slider-vertical" style="height:200px;"></div>
<div id="s-vrange" class="ui-slider ui-slider-vertical" style="height:250px;"></div>
<script>
function snapValue(v, min, max, step) {
const clamped = Math.max(min, Math.min(max, v));
const aligned = min + Math.round((clamped - min) / step) * step;
return Math.max(min, Math.min(max, aligned));
}
function createSlider(id, opts = {}) {
const el = document.getElementById(id);
const min = opts.min ?? 0;
const max = opts.max ?? 100;
const step = opts.step ?? 1;
const orientation = opts.orientation || "horizontal";
const range = opts.range ?? false;
let value = snapValue(opts.value ?? min, min, max, step);
let values = opts.values ? opts.values.map(v => snapValue(v, min, max, step)) : null;
const rangeDiv = document.createElement("div");
rangeDiv.className = "ui-slider-range";
el.appendChild(rangeDiv);
const handleCount = values ? 2 : 1;
const handles = [];
for (let i = 0; i < handleCount; i++) {
const h = document.createElement("span");
h.className = "ui-slider-handle";
h.tabIndex = 0;
el.appendChild(h);
handles.push(h);
}
function pct(v) { return ((v - min) / (max - min)) * 100; }
function render() {
if (values) {
const p0 = pct(values[0]), p1 = pct(values[1]);
if (orientation === "horizontal") {
handles[0].style.left = p0 + "%";
handles[1].style.left = p1 + "%";
rangeDiv.style.left = p0 + "%";
rangeDiv.style.width = (p1 - p0) + "%";
} else {
handles[0].style.bottom = p0 + "%";
handles[1].style.bottom = p1 + "%";
rangeDiv.style.bottom = p0 + "%";
rangeDiv.style.height = (p1 - p0) + "%";
}
} else {
const p = pct(value);
if (orientation === "horizontal") {
handles[0].style.left = p + "%";
if (range === "min") { rangeDiv.style.left = "0%"; rangeDiv.style.width = p + "%"; }
else if (range === "max") { rangeDiv.style.left = p + "%"; rangeDiv.style.width = (100 - p) + "%"; }
} else {
handles[0].style.bottom = p + "%";
if (range === "min") { rangeDiv.style.bottom = "0%"; rangeDiv.style.height = p + "%"; }
else if (range === "max") { rangeDiv.style.bottom = p + "%"; rangeDiv.style.height = (100 - p) + "%"; }
}
}
}
function setValue(next) {
value = snapValue(next, min, max, step);
render();
if (opts.onChange) opts.onChange(value);
return value;
}
function setValues(idx, next) {
let v = snapValue(next, min, max, step);
if (idx === 0) v = Math.min(v, values[1]);
if (idx === 1) v = Math.max(v, values[0]);
values[idx] = v;
render();
if (opts.onChange) opts.onChange(values.slice());
return values.slice();
}
el.addEventListener("keydown", e => {
if (values) return;
if (e.key === "ArrowRight" || e.key === "ArrowUp") setValue(value + step);
else if (e.key === "ArrowLeft" || e.key === "ArrowDown") setValue(value - step);
});
render();
return { getValue: () => value, getValues: () => values.slice(), setValue, setValues, rangeDiv, handles };
}
window.sDefault = createSlider("s-default", { min: 0, max: 100, value: 0 });
window.sStep = createSlider("s-step", {
min: 0, max: 500, step: 50, value: 100,
onChange(v) { document.getElementById("step-amount").value = "$" + v; }
});
document.getElementById("step-amount").value = "$" + window.sStep.getValue();
function hexFromRGB(r, g, b) {
return [r, g, b].map(n => n.toString(16).padStart(2, "0")).join("").toUpperCase();
}
window.rgbVals = { r: 255, g: 140, b: 60 };
window.refreshSwatch = () => {
const hex = hexFromRGB(window.rgbVals.r, window.rgbVals.g, window.rgbVals.b);
document.getElementById("swatch").style.backgroundColor = "#" + hex;
return "#" + hex;
};
window.eqVals = [88, 77, 55, 33, 40, 45, 70];
window.sRange = createSlider("s-range", { range: true, min: 0, max: 500, values: [75, 300] });
window.sRmax = createSlider("s-rmax", { range: "max", min: 1, max: 10, value: 2 });
window.sRmin = createSlider("s-rmin", { range: "min", min: 1, max: 700, value: 37 });
const minbeds = document.getElementById("minbeds");
window.sSelectVal = minbeds.selectedIndex + 1;
minbeds.addEventListener("change", () => { window.sSelectVal = minbeds.selectedIndex + 1; });
window.slideSelectTo = v => { window.sSelectVal = v; minbeds.selectedIndex = v - 1; };
window.calcScrollbar = (paneW, contentW, sliderVal) => {
const marginLeft = Math.round((sliderVal / 100) * (paneW - contentW));
const remainder = contentW - paneW;
const proportion = remainder / contentW;
const handleSize = Math.round(paneW - proportion * paneW);
return { marginLeft, handleSize };
};
window.sVert = createSlider("s-vert", { orientation: "vertical", range: "min", min: 0, max: 100, value: 60 });
window.sVrange = createSlider("s-vrange", { orientation: "vertical", range: true, min: 0, max: 100, values: [17, 67] });
</script>
</body>
</html>
"""
def main():
cases = []
with sync_playwright() as p:
try:
browser = p.chromium.launch(headless=True)
except Exception:
browser = p.chromium.launch(headless=True, channel="chrome")
page = browser.new_page()
page.set_content(HTML_DOC)
# Case 1: Default keyboard step + step=50 snapping
page.focus("#s-default")
page.keyboard.press("ArrowRight")
page.keyboard.press("ArrowRight")
page.keyboard.press("ArrowLeft")
default_after_keys = page.evaluate("() => window.sDefault.getValue()")
snap1 = page.evaluate("() => window.sStep.setValue(127)")
snap2 = page.evaluate("() => window.sStep.setValue(274)")
page.focus("#s-step")
page.keyboard.press("ArrowRight")
step_after_key = page.evaluate("() => ({ val: window.sStep.getValue(), label: document.getElementById('step-amount').value })")
res1 = {"defaultAfterKeys": default_after_keys, "snap127": snap1, "snap274": snap2, "afterArrowRight": step_after_key}
exp1 = {"defaultAfterKeys": 1, "snap127": 150, "snap274": 250, "afterArrowRight": {"val": 300, "label": "$300"}}
cases.append(dict(name="slider_default_keyboard_and_step", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: RGB color picker swatch + multi-slider equalizer
res2 = page.evaluate("""() => {
const initHex = window.refreshSwatch();
window.rgbVals.g = 200;
const nextHex = window.refreshSwatch();
const swatchBg = getComputedStyle(document.getElementById("swatch")).backgroundColor;
return { initHex, nextHex, swatchBg, masterInit: 60, eqCount: window.eqVals.length, eqValues: window.eqVals };
}""")
exp2 = {
"initHex": "#FF8C3C",
"nextHex": "#FFC83C",
"swatchBg": "rgb(255, 200, 60)",
"masterInit": 60,
"eqCount": 7,
"eqValues": [88, 77, 55, 33, 40, 45, 70],
}
cases.append(dict(name="slider_rgb_colorpicker_and_multi_eq", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Dual range (clamping), fixed max, fixed min
res3 = page.evaluate("""() => {
const initPair = window.sRange.getValues();
const clampedLow = window.sRange.setValues(0, 400); // clamped at upper 300
window.sRange.setValues(0, 100);
const updatedPair = window.sRange.setValues(1, 350);
const rmaxStyle = { left: window.sRmax.rangeDiv.style.left, width: window.sRmax.rangeDiv.style.width };
const rminVal = window.sRmin.getValue();
return {
initPair,
clampedLow,
updatedLabel: "$" + updatedPair[0] + " - $" + updatedPair[1],
rmaxVal: window.sRmax.getValue(),
rmaxFillsRight: parseFloat(rmaxStyle.width) > 85,
rminVal,
rminFillsLeft: window.sRmin.rangeDiv.style.left === "0%"
};
}""")
exp3 = {
"initPair": [75, 300],
"clampedLow": [300, 300],
"updatedLabel": "$100 - $350",
"rmaxVal": 2,
"rmaxFillsRight": True,
"rminVal": 37,
"rminFillsLeft": True,
}
cases.append(dict(name="slider_range_modes", expected=exp3, actual=res3, passed=(res3 == exp3)))
# Case 4: Select bidirectional sync + slider scrollbar math
page.select_option("#minbeds", "4")
after_select = page.evaluate("() => window.sSelectVal")
page.evaluate("() => window.slideSelectTo(6)")
after_slide = page.evaluate("() => ({ selectIdx: document.getElementById('minbeds').selectedIndex, val: window.sSelectVal })")
scroll_50 = page.evaluate("() => window.calcScrollbar(440, 2440, 50)")
res4 = {"afterSelect4": after_select, "afterSlide6": after_slide, "scrollAt50": scroll_50}
exp4 = {
"afterSelect4": 4,
"afterSlide6": {"selectIdx": 5, "val": 6},
"scrollAt50": {"marginLeft": -1000, "handleSize": 79},
}
cases.append(dict(name="slider_select_binding_and_scrollbar", expected=exp4, actual=res4, passed=(res4 == exp4)))
# Case 5: Vertical single & vertical dual-handle range
res5 = page.evaluate("""() => {
const singleBottom = window.sVert.handles[0].style.bottom;
const vInitRange = { bottom: window.sVrange.rangeDiv.style.bottom, height: window.sVrange.rangeDiv.style.height };
window.sVrange.setValues(0, 25);
const vNext = window.sVrange.setValues(1, 80);
return {
singleBottom,
vInitRange,
vUpdatedLabel: "$" + vNext[0] + " - $" + vNext[1],
vUpdatedHeight: window.sVrange.rangeDiv.style.height
};
}""")
exp5 = {
"singleBottom": "60%",
"vInitRange": {"bottom": "17%", "height": "50%"},
"vUpdatedLabel": "$25 - $80",
"vUpdatedHeight": "55%",
}
cases.append(dict(name="slider_vertical_and_vertical_range", expected=exp5, actual=res5, passed=(res5 == exp5)))
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-slider-lab/explore-example-slider.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-example-slider.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a937.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip