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

在离线 Chromium 中验证 Progressbar 确定值、自定义标签事件与不确定态切换

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-example-progressbar.py
explore-example-progressbar.py177 行
"""Offline Playwright Chromium lab for jQuery UI Ch 28: Progressbar."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Progressbar Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; }
  .ui-progressbar { position: relative; width: 300px; height: 26px; border: 1px solid #999; background: #f5f5f5; margin-bottom: 12px; }
  .ui-progressbar-value { height: 100%; background-color: #ccc; width: 0%; }
  .ui-progressbar-indeterminate .ui-progressbar-value { width: 100%; background-image: repeating-linear-gradient(45deg,#ccc,#ccc 10px,#eee 10px,#eee 20px); }
  .progress-label { position: absolute; left: 50%; top: 4px; font-weight: bold; }
</style>
</head>
<body>
<div id="pb-default" class="ui-progressbar" role="progressbar" aria-valuemin="0" aria-valuemax="100">
  <div class="ui-progressbar-value"></div>
</div>

<div id="pb-label" class="ui-progressbar" role="progressbar" aria-valuemin="0" aria-valuemax="100">
  <div class="ui-progressbar-value"></div>
  <div class="progress-label">加载...</div>
</div>

<div id="pb-toggle" class="ui-progressbar" role="progressbar" aria-valuemin="0" aria-valuemax="100">
  <div class="ui-progressbar-value"></div>
</div>
<button id="numButton">确定值</button>
<button id="falseButton">不确定</button>
<button id="colorButton">切换颜色</button>

<script>
function createProgressbar(id, opts = {}) {
  const root = document.getElementById(id);
  const bar = root.querySelector(".ui-progressbar-value");
  const max = opts.max || 100;
  let value = opts.value !== undefined ? opts.value : 0;

  function render() {
    if (value === false) {
      root.classList.add("ui-progressbar-indeterminate");
      root.removeAttribute("aria-valuenow");
      bar.style.width = "100%";
    } else {
      const clamped = Math.max(0, Math.min(max, value));
      value = clamped;
      root.classList.remove("ui-progressbar-indeterminate");
      root.setAttribute("aria-valuenow", String(clamped));
      bar.style.width = Math.round((clamped / max) * 100) + "%";
    }
  }

  function setValue(next) {
    const prev = value;
    value = next;
    render();
    if (next !== prev && opts.change) opts.change(value);
    if (value === max && opts.complete) opts.complete();
  }

  render();
  return { getValue: () => value, setValue, bar, root };
}

window.pbDefault = createProgressbar("pb-default", { value: 37 });

const labelEl = document.querySelector("#pb-label .progress-label");
window.labelHistory = [];
window.pbLabel = createProgressbar("pb-label", {
  value: false,
  change(v) {
    if (v !== false) labelEl.textContent = v + "%";
    window.labelHistory.push(labelEl.textContent);
  },
  complete() {
    labelEl.textContent = "完成!";
    window.labelHistory.push(labelEl.textContent);
  }
});

window.pbToggle = createProgressbar("pb-toggle", { value: false });
document.getElementById("numButton").addEventListener("click", () => window.pbToggle.setValue(64));
document.getElementById("falseButton").addEventListener("click", () => window.pbToggle.setValue(false));
document.getElementById("colorButton").addEventListener("click", () => {
  window.pbToggle.bar.style.backgroundColor = "#2a9d8f";
});
</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 determinate progressbar at value=37
        res1 = page.evaluate("""() => {
            const root = document.getElementById("pb-default");
            return {
                value: window.pbDefault.getValue(),
                ariaNow: root.getAttribute("aria-valuenow"),
                ariaMax: root.getAttribute("aria-valuemax"),
                widthStyle: root.querySelector(".ui-progressbar-value").style.width,
                indeterminate: root.classList.contains("ui-progressbar-indeterminate")
            };
        }""")
        exp1 = {"value": 37, "ariaNow": "37", "ariaMax": "100", "widthStyle": "37%", "indeterminate": False}
        cases.append(dict(name="progressbar_default_determinate", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Custom label with indeterminate init, change updates, and complete callback
        res2 = page.evaluate("""() => {
            const initLabel = document.querySelector("#pb-label .progress-label").textContent;
            const initIndeterminate = document.getElementById("pb-label").classList.contains("ui-progressbar-indeterminate");
            window.pbLabel.setValue(25);
            window.pbLabel.setValue(50);
            window.pbLabel.setValue(100);
            return {
                initLabel,
                initIndeterminate,
                history: window.labelHistory,
                finalLabel: document.querySelector("#pb-label .progress-label").textContent
            };
        }""")
        exp2 = {
            "initLabel": "加载...",
            "initIndeterminate": True,
            "history": ["25%", "50%", "100%", "完成!"],
            "finalLabel": "完成!",
        }
        cases.append(dict(name="progressbar_custom_label_events", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Indeterminate <-> determinate toggle and bar color update
        init_indet = page.evaluate("""() => document.getElementById("pb-toggle").classList.contains("ui-progressbar-indeterminate")""")
        page.click("#numButton")
        det_state = page.evaluate("""() => ({
            ariaNow: document.getElementById("pb-toggle").getAttribute("aria-valuenow"),
            width: document.querySelector("#pb-toggle .ui-progressbar-value").style.width,
            indet: document.getElementById("pb-toggle").classList.contains("ui-progressbar-indeterminate")
        })""")
        page.click("#colorButton")
        bg_color = page.evaluate("""() => getComputedStyle(document.querySelector("#pb-toggle .ui-progressbar-value")).backgroundColor""")
        page.click("#falseButton")
        back_indet = page.evaluate("""() => ({
            indet: document.getElementById("pb-toggle").classList.contains("ui-progressbar-indeterminate"),
            ariaNow: document.getElementById("pb-toggle").getAttribute("aria-valuenow")
        })""")
        res3 = {
            "initIndeterminate": init_indet,
            "determinate": det_state,
            "barColor": bg_color,
            "backToIndeterminate": back_indet,
        }
        exp3 = {
            "initIndeterminate": True,
            "determinate": {"ariaNow": "64", "width": "64%", "indet": False},
            "barColor": "rgb(42, 157, 143)",
            "backToIndeterminate": {"indet": True, "ariaNow": None},
        }
        cases.append(dict(name="progressbar_indeterminate_toggle_and_color", expected=exp3, actual=res3, passed=(res3 == exp3)))

        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-progressbar-lab/explore-example-progressbar.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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