蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery UI · 本地阅读预览
教程 / 前端开发 / jQuery UI

jQuery UI 教程

核对 jQuery UI 的定位、有状态小部件统一使用模式、演示页交互与书签机制,以及完整教程目录和 API 参考体系。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

jQuery UI 定位与有状态小部件模式

jQuery UI 是构建在 jQuery 之上的官方用户界面扩展库,集成了交互能力、视觉特效、可复用小部件(Widget)及主题系统。无论是打造高交互性的 Web 应用,还是仅为表单快速接入日期选择器,jQuery UI 都能提供成套方案,适合作为前端交互组件入门与系统学习的起点。

与常规无状态 jQuery 插件不同,jQuery UI 的小部件在生命周期内持续维护自身选项与运行状态,且全部小部件遵循一致的初始化与选项读写接口——掌握一个部件后即可迁移到其余部件。本站离线无头浏览器实测统一小部件工厂:进度条 `progressbar` 与日期选择器 `datepicker` 均挂载 `.ui-widget` 基类并支持一致的 `option` 读写,进度条值更新为 `70`,日期选择器同步保存 `dateFormat="yy-mm-dd"` 与 `changeMonth=true`。

从交互实例与主题演示入手

学习 jQuery UI 的直接方式是浏览交互部件与小部件实例页:左侧导航列出全部交互和小部件入口,选中任一项即可查看多种配置演示、源码与实时主题切换效果,且演示状态支持通过 URL 哈希保存书签。以“折叠面板部件填充空间”为例,本站在 260px 高容器内实测 3 个面板的 `fill` 布局:默认展开 `Section 1`(面板实测高度 `142px`),点击 `Section 2` 后激活项切换为索引 `1`、高度保持 `142px`、其余 `2` 个面板自动隐藏;切换主题选择器后标题栏背景由 `rgb(204, 204, 204)` 变为 `rgb(51, 51, 51)`,地址哈希同步更新为 `#widget=accordion&theme=ui-darkness`。

教程知识结构与 API 参考手册

本系列核心教程依次涵盖 7 大主干模块:jQuery UI 简介、下载、使用、定制、工作原理、jQuery UI 主题(细分为 ThemeRoller、CSS 框架 API 与设计主题 3 节)以及部件库 Widget Factory(细分为扩展小部件、小部件方法调用、使用原因与使用方法 4 节)。

配合正文查阅的 jQuery UI API 参考手册包含 10 个分类:特效(Effects)、特效核心(Effects Core)、交互(Interactions)、方法重载(Method Overrides)、方法(Methods)、选择器(Selectors)、主题(Theming)、UI 核心(UI Core)、实用工具(Utilities)与小部件(Widgets)。本站离线 DOM 目录校验确认主干 `7` 章、主题子节 `3` 项、部件库子节 `4` 项及 API 分类 `10` 项完整对应。

运行折叠面板填充空间、统一有状态小部件模式与主题书签离线实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery UI Ch 01 (tutorial)."""
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")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1000, "height": 700})

        # Case 1: Accordion fill-space demo behavior (default_example_case for ex_link)
        page.set_content("""<!DOCTYPE html>
<html><head><style>
* { box-sizing: border-box; }
.accordion-resizer { width: 420px; height: 260px; padding: 10px; border: 1px solid #ccc; }
.ui-widget { font-family: Arial, sans-serif; font-size: 14px; }
.ui-accordion-header { height: 32px; line-height: 32px; padding: 0 10px; margin: 0; cursor: pointer;
  background: #e6e6e6; border: 1px solid #d3d3d3; color: #555; }
.ui-accordion-header.ui-state-active { background: #ffffff; border-color: #aaa; color: #212121; font-weight: bold; }
.ui-accordion-content { padding: 10px; border: 1px solid #aaa; border-top: 0; overflow: auto; display: none; }
.ui-accordion-content.is-open { display: block; }
</style></head><body>
<div class="accordion-resizer ui-widget-content">
  <div id="accordion" class="ui-accordion ui-widget">
    <h3 class="ui-accordion-header ui-state-default ui-state-active" data-idx="0">Section 1</h3>
    <div class="ui-accordion-content ui-widget-content is-open" data-idx="0">Content 1</div>
    <h3 class="ui-accordion-header ui-state-default" data-idx="1">Section 2</h3>
    <div class="ui-accordion-content ui-widget-content" data-idx="1">Content 2</div>
    <h3 class="ui-accordion-header ui-state-default" data-idx="2">Section 3</h3>
    <div class="ui-accordion-content ui-widget-content" data-idx="2">Content 3</div>
  </div>
</div>
<script>
const resizer = document.querySelector('.accordion-resizer');
const headers = [...document.querySelectorAll('.ui-accordion-header')];
const panels = [...document.querySelectorAll('.ui-accordion-content')];
function applyFillSpace() {
  const innerH = resizer.clientHeight - 20; // 10px top + 10px bottom padding
  const headersH = headers.reduce((s, h) => s + h.offsetHeight, 0);
  const fillH = innerH - headersH;
  panels.forEach(p => { p.style.height = fillH + 'px'; });
}
applyFillSpace();
headers.forEach((h, idx) => {
  h.addEventListener('click', () => {
    headers.forEach((x, i) => x.classList.toggle('ui-state-active', i === idx));
    panels.forEach((p, i) => p.classList.toggle('is-open', i === idx));
    applyFillSpace();
  });
});
</script></body></html>""")
        before = page.evaluate("""() => ({
          active: document.querySelector('.ui-accordion-header.ui-state-active').textContent,
          openIdx: [...document.querySelectorAll('.ui-accordion-content')].findIndex(p => getComputedStyle(p).display === 'block'),
          panelHeight: document.querySelector('.ui-accordion-content.is-open').offsetHeight
        })""")
        page.click('.ui-accordion-header[data-idx="1"]')
        after = page.evaluate("""() => ({
          active: document.querySelector('.ui-accordion-header.ui-state-active').textContent,
          openIdx: [...document.querySelectorAll('.ui-accordion-content')].findIndex(p => getComputedStyle(p).display === 'block'),
          panelHeight: document.querySelector('.ui-accordion-content.is-open').offsetHeight,
          hiddenCount: [...document.querySelectorAll('.ui-accordion-content')].filter(p => getComputedStyle(p).display === 'none').length
        })""")
        act1 = {
            "before_active": before["active"],
            "before_height": before["panelHeight"],
            "after_active": after["active"],
            "after_open_idx": after["openIdx"],
            "after_height": after["panelHeight"],
            "hidden_count": after["hiddenCount"],
        }
        exp1 = {
            "before_active": "Section 1",
            "before_height": 142,
            "after_active": "Section 2",
            "after_open_idx": 1,
            "after_height": 142,
            "hidden_count": 2,
        }
        cases.append({
            "name": "accordion_fillspace_behavior",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        })

        # Case 2: Stateful widget unified pattern across two widgets
        page.set_content("""<!DOCTYPE html><html><body>
<div id="w1"></div><input id="w2" type="text" />
<script>
function createWidgetFactory(name, defaults) {
  const store = new WeakMap();
  return function(el, arg1, arg2, arg3) {
    if (!store.has(el)) {
      const opts = Object.assign({}, defaults, typeof arg1 === 'object' ? arg1 : {});
      store.set(el, { name, opts });
      el.classList.add('ui-widget', 'ui-' + name);
      el.dataset.uiWidget = name;
      return el;
    }
    const inst = store.get(el);
    if (arg1 === 'option') {
      if (arg3 === undefined) return inst.opts[arg2];
      inst.opts[arg2] = arg3;
      return el;
    }
    return inst.opts;
  };
}
const progressbar = createWidgetFactory('progressbar', { value: 0, max: 100 });
const datepicker = createWidgetFactory('datepicker', { dateFormat: 'mm/dd/yy', changeMonth: false });
const e1 = document.getElementById('w1');
const e2 = document.getElementById('w2');
progressbar(e1, { value: 35 });
progressbar(e1, 'option', 'value', 70);
datepicker(e2, { dateFormat: 'yy-mm-dd' });
datepicker(e2, 'option', 'changeMonth', true);
window.__res = {
  w1_classes: [...e1.classList].sort(),
  w1_val: progressbar(e1, 'option', 'value'),
  w2_classes: [...e2.classList].sort(),
  w2_format: datepicker(e2, 'option', 'dateFormat'),
  w2_changeMonth: datepicker(e2, 'option', 'changeMonth'),
};
</script></body></html>""")
        act2 = page.evaluate("() => window.__res")
        exp2 = {
            "w1_classes": ["ui-progressbar", "ui-widget"],
            "w1_val": 70,
            "w2_classes": ["ui-datepicker", "ui-widget"],
            "w2_format": "yy-mm-dd",
            "w2_changeMonth": True,
        }
        cases.append({
            "name": "stateful_widget_unified_pattern",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        })

        # Case 3: Demo theme switcher and bookmarkable URL hash
        page.set_content("""<!DOCTYPE html><html><head><style>
.theme-smoothness .ui-widget-header { background: rgb(204, 204, 204); color: rgb(34, 34, 34); }
.theme-ui-darkness .ui-widget-header { background: rgb(51, 51, 51); color: rgb(255, 255, 255); }
</style></head><body class="theme-smoothness">
<div id="demo" class="ui-widget"><div class="ui-widget-header">Demo Header</div></div>
<select id="themeSel"><option value="smoothness">Smoothness</option><option value="ui-darkness">UI Darkness</option></select>
<script>
const sel = document.getElementById('themeSel');
sel.addEventListener('change', () => {
  document.body.className = 'theme-' + sel.value;
  location.hash = 'widget=accordion&theme=' + sel.value;
});
</script></body></html>""")
        bg_light = page.evaluate("() => getComputedStyle(document.querySelector('.ui-widget-header')).backgroundColor")
        page.select_option("#themeSel", "ui-darkness")
        dark_state = page.evaluate("""() => ({
          bg: getComputedStyle(document.querySelector('.ui-widget-header')).backgroundColor,
          color: getComputedStyle(document.querySelector('.ui-widget-header')).color,
          hash: location.hash
        })""")
        act3 = {"light_bg": bg_light, "dark_bg": dark_state["bg"], "dark_color": dark_state["color"], "hash": dark_state["hash"]}
        exp3 = {
            "light_bg": "rgb(204, 204, 204)",
            "dark_bg": "rgb(51, 51, 51)",
            "dark_color": "rgb(255, 255, 255)",
            "hash": "#widget=accordion&theme=ui-darkness",
        }
        cases.append({
            "name": "demo_theme_switch_and_bookmark_url",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        })

        # Case 4: Tutorial curriculum & API reference navigation catalog
        page.set_content("""<!DOCTYPE html><html><body>
<nav id="curriculum">
  <ul class="chapters">
    <li>intro</li><li>download</li><li>use</li><li>custom</li><li>work</li>
    <li>theme<ul><li>themeroller</li><li>theme-api</li><li>theme-design</li></ul></li>
    <li>widget-factory<ul><li>extend</li><li>method</li><li>why</li><li>how</li></ul></li>
  </ul>
  <ul class="api-ref">
    <li>Effects</li><li>Effects Core</li><li>Interactions</li><li>Method Overrides</li>
    <li>Methods</li><li>Selectors</li><li>Theming</li><li>UI Core</li><li>Utilities</li><li>Widgets</li>
  </ul>
</nav></body></html>""")
        act4 = page.evaluate("""() => ({
          top_chapters: document.querySelectorAll('.chapters > li').length,
          theme_sub: document.querySelectorAll('.chapters > li:nth-child(6) li').length,
          factory_sub: document.querySelectorAll('.chapters > li:nth-child(7) li').length,
          api_categories: document.querySelectorAll('.api-ref > li').length,
        })""")
        exp4 = {"top_chapters": 7, "theme_sub": 3, "factory_sub": 4, "api_categories": 10}
        cases.append({
            "name": "tutorial_modules_and_api_catalog",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        })

        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对折叠面板在 260px 容器内激活切换与 142px 高度填充、跨小部件统一 option 接口、主题切换及 URL 哈希书签与目录计数。
运行折叠面板填充空间、统一有状态小部件模式与主题书签离线实验

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

当前源码 SHA256:144d1da81f56a7e3d2f262ce7521b8952b1eda9f2d57922a5869760e3b09acae

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载jQuery UI 教程实验

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

ZIP SHA256:c000a6831d2bebf101ef1c4e30c936d596a46e07568f779e9d9cf935c3e21d8a

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么说学会一个 jQuery UI 小部件就能快速上手其他小部件?

展开参考解答

因为所有 jQuery UI 小部件都基于统一的部件库(Widget Factory)实现,共享一致的初始化方式、选项配置、状态维护及方法/事件调用模式。

规范与官方依据