蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Slider 选项对象覆写、ThemeRoller 实时调参预览与 CSS 书签 URL 还原离线实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-custom.py
explore-custom.py181 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/jqueryui-custom-lab/explore-custom.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-custom.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a917.zip

下载课程关联工程包:jQuery UI

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习