jQuery UI 定制
核对通过选项对象 `{ }` 覆盖小部件默认行为、利用 ThemeRoller 可视化调节主题样式,以及通过 CSS 注释链接复现和下载自定义主题的流程。
学完这一章,你能够
- 核对通过选项对象 `{ }` 覆盖小部件默认行为、利用 ThemeRoller 可视化调节主题样式,以及通过 CSS 注释链接复现和下载自定义主题的流程。
通过选项对象定制小部件行为
除使用 Download Builder 裁剪组件外,jQuery UI 还支持行为与视觉两个维度的深度定制。每个插件均预设了最常见的默认配置,只需在初始化时传入选项对象即可覆盖默认值。例如 `slider` 默认呈水平方向,传入 `{ orientation: "vertical" }` 即可改为垂直滑块。本站离线实测:默认水平滑块具有 `.ui-slider-horizontal` 且实测尺寸为 `202px × 14px`,传入垂直选项后切换为 `.ui-slider-vertical` 且尺寸变为 `14px × 152px`。
同一选项对象 `{ }` 内可按逗号分隔同时传入多个配置项,例如 `$( "#mySliderDiv" ).slider({ orientation: "vertical", min: 0, max: 150, value: 50 });`。务必使用大括号包裹键值对,各部件完整选项清单可对照实例与 API 文档。本站实测该多选项配置:滑块手柄初始定位在 `bottom: 33.33%`(`(50-0)/(150-0)`),越界写入 `200` 与 `-10` 时自动钳制在 `150` 与 `0`。
借助 ThemeRoller 视觉定制与下载主题
在视觉外观方面,官方提供的 ThemeRoller Web 应用为全部 jQuery UI 小部件提供所见即所得的定制界面:调节左侧各样式调节杆(levers)时,右侧小部件预览区会即时重绘;同时 Gallery 选项卡内置了与 Download Builder 一致的预设主题,既可直接下载也能以此为基底微调。本站离线构建简化版 ThemeRoller 调节栏实测:将标题背景、圆角与字号分别由 `#cccccc`/`4px`/`12px` 调至 `#4a7c24`/`8px`/`14px` 后,预览区标题背景立刻变为 `rgb(74, 124, 36)`,按钮圆角同步更新为 `8px`。
完成配色与圆角调整后点击顶部 "Download theme",页面会自动跳转至 Download Builder 并在主题下拉框中选中刚设计的自定义主题;解压下载包即可在 `example.html` 中预览整套部件效果。若日后需返工修改,打开生成的主题 CSS 文件约第 43 行的 `To view and modify this theme, visit ...` 注释链接即可直接回到 ThemeRoller 恢复全部参数。本站实测解析该注释查询串可无损还原 `bgColorHeader=4a7c24`、`cornerRadius=8px`、`fsDefault=1.1em`。
运行 Slider 选项对象覆写、ThemeRoller 实时调参预览与 CSS 书签 URL 还原离线实验
展开查看收起
"""Offline Playwright Chromium lab for jQuery UI Ch 05 (custom)."""
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
SLIDER_HTML = """<!DOCTYPE html><html><head><style>
.ui-slider { position: relative; border: 1px solid #aaa; background: #fff; }
.ui-slider-horizontal { width: 200px; height: 12px; }
.ui-slider-vertical { width: 12px; height: 150px; }
.ui-slider-handle { position: absolute; width: 16px; height: 16px; background: #e6e6e6; border: 1px solid #999; }
</style></head><body>
<div id="mySliderDiv"></div>
<script>
window.$ = function(sel) {
const el = document.querySelector(sel);
return {
slider(opts) {
const cfg = Object.assign({ orientation: 'horizontal', min: 0, max: 100, value: 0 }, opts || {});
const clamp = v => Math.min(cfg.max, Math.max(cfg.min, v));
cfg.value = clamp(cfg.value);
el.className = 'ui-slider ui-widget ui-widget-content ui-slider-' + cfg.orientation;
el.innerHTML = '<span class="ui-slider-handle ui-state-default"></span>';
const handle = el.querySelector('.ui-slider-handle');
const pct = ((cfg.value - cfg.min) / (cfg.max - cfg.min)) * 100;
if (cfg.orientation === 'vertical') {
handle.style.bottom = pct.toFixed(2) + '%';
} else {
handle.style.left = pct.toFixed(2) + '%';
}
el.__sliderCfg = cfg;
el.__setVal = (v) => {
cfg.value = clamp(v);
const p = ((cfg.value - cfg.min) / (cfg.max - cfg.min)) * 100;
if (cfg.orientation === 'vertical') handle.style.bottom = p.toFixed(2) + '%';
else handle.style.left = p.toFixed(2) + '%';
return cfg.value;
};
return this;
}
};
};
</script></body></html>"""
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 960, "height": 640})
# Case 1: Default horizontal slider vs single orientation option
page.set_content(SLIDER_HTML)
page.evaluate('() => $( "#mySliderDiv" ).slider()')
def_metrics = page.evaluate("""() => {
const el = document.getElementById('mySliderDiv');
return { cls: el.classList.contains('ui-slider-horizontal'), w: el.offsetWidth, h: el.offsetHeight };
}""")
page.evaluate('() => $( "#mySliderDiv" ).slider({ orientation: "vertical" })')
vert_metrics = page.evaluate("""() => {
const el = document.getElementById('mySliderDiv');
return { cls: el.classList.contains('ui-slider-vertical'), w: el.offsetWidth, h: el.offsetHeight };
}""")
act1 = {"default_horizontal": def_metrics, "vertical_option": vert_metrics}
exp1 = {
"default_horizontal": {"cls": True, "w": 202, "h": 14},
"vertical_option": {"cls": True, "w": 14, "h": 152},
}
cases.append({
"name": "slider_default_vs_vertical_option",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
})
# Case 2: Multiple comma-separated options inside {}
page.evaluate("""() => $( "#mySliderDiv" ).slider({
orientation: "vertical",
min: 0,
max: 150,
value: 50
})""")
act2 = page.evaluate("""() => {
const el = document.getElementById('mySliderDiv');
const handle = el.querySelector('.ui-slider-handle');
const initialPct = handle.style.bottom;
const clampedHi = el.__setVal(200);
const clampedLo = el.__setVal(-10);
return { cfg_min: el.__sliderCfg.min, cfg_max: el.__sliderCfg.max, initial_bottom: initialPct, clamped_hi: clampedHi, clamped_lo: clampedLo };
}""")
exp2 = {"cfg_min": 0, "cfg_max": 150, "initial_bottom": "33.33%", "clamped_hi": 150, "clamped_lo": 0}
cases.append({
"name": "slider_multi_options_object",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
})
# Case 3: ThemeRoller live lever preview
page.set_content("""<!DOCTYPE html><html><head><style>
:root { --hdr-bg: #cccccc; --radius: 4px; --font-sz: 12px; }
.ui-widget { font-size: var(--font-sz); }
.ui-widget-header { background: var(--hdr-bg); border-radius: var(--radius); padding: 6px; }
.ui-button { background: var(--hdr-bg); border-radius: var(--radius); padding: 4px 10px; }
</style></head><body>
<input id="leverBg" value="#4a7c24" /><input id="leverRad" value="8px" /><input id="leverFont" value="14px" />
<button id="applyBtn">Apply</button>
<div id="preview" class="ui-widget">
<div id="pHdr" class="ui-widget-header">Accordion Header</div>
<button id="pBtn" class="ui-button">A button element</button>
</div>
<script>
document.getElementById('applyBtn').addEventListener('click', () => {
const root = document.documentElement.style;
root.setProperty('--hdr-bg', document.getElementById('leverBg').value);
root.setProperty('--radius', document.getElementById('leverRad').value);
root.setProperty('--font-sz', document.getElementById('leverFont').value);
});
</script></body></html>""")
before3 = page.evaluate("""() => ({
bg: getComputedStyle(document.getElementById('pHdr')).backgroundColor,
rad: getComputedStyle(document.getElementById('pHdr')).borderRadius,
fs: getComputedStyle(document.getElementById('preview')).fontSize
})""")
page.click("#applyBtn")
after3 = page.evaluate("""() => ({
bg: getComputedStyle(document.getElementById('pHdr')).backgroundColor,
rad: getComputedStyle(document.getElementById('pHdr')).borderRadius,
fs: getComputedStyle(document.getElementById('preview')).fontSize,
btn_rad: getComputedStyle(document.getElementById('pBtn')).borderRadius
})""")
act3 = {"before": before3, "after": after3}
exp3 = {
"before": {"bg": "rgb(204, 204, 204)", "rad": "4px", "fs": "12px"},
"after": {"bg": "rgb(74, 124, 36)", "rad": "8px", "fs": "14px", "btn_rad": "8px"},
}
cases.append({
"name": "themeroller_live_lever_preview",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
})
# Case 4: ThemeRoller CSS line-43 bookmark URL & example.html verification
page.set_content("""<!DOCTYPE html><html><body><script>
const cssHeaderComment = '/* To view and modify this theme, visit http://jqueryui.com/themeroller/?bgColorHeader=4a7c24&cornerRadius=8px&fsDefault=1.1em */';
const match = cssHeaderComment.match(/\\?([^\\s*]+)/);
const params = Object.fromEntries(new URLSearchParams(match[1]).entries());
window.__urlCheck = {
extracted_params: params,
example_file: 'example.html',
restored_ok: params.bgColorHeader === '4a7c24' && params.cornerRadius === '8px' && params.fsDefault === '1.1em'
};
</script></body></html>""")
act4 = page.evaluate("() => window.__urlCheck")
exp4 = {
"extracted_params": {"bgColorHeader": "4a7c24", "cornerRadius": "8px", "fsDefault": "1.1em"},
"example_file": "example.html",
"restored_ok": True,
}
cases.append({
"name": "themeroller_url_bookmark_and_example_html",
"expected": exp4,
"actual": act4,
"passed": act4 == exp4,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
打开下载包中的主题 CSS 文件,找到顶部注释(约第 43 行)中以 `To view and modify this theme, visit ...` 开头的 URL,在浏览器打开即可在 ThemeRoller 中自动加载原有全部配置项。