蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery UI 教程目录 43章
jQuery UI / LEARN BY DOING

jQuery UI 实例

总览 jQuery UI 交互、小部件、特效与实用工具四大模块的全部示例分类,并在离线 Chromium 中实测四类代表能力。

学完这一章,你能够

  • 总览 jQuery UI 交互、小部件、特效与实用工具四大模块的全部示例分类,并在离线 Chromium 中实测四类代表能力。

jQuery UI 四大能力模块总览

jQuery UI 将常用前端界面能力划分为交互(Interactions)、小部件(Widgets)、特效(Effects)与实用工具(Utilities)四大模块,并配套统一主题体系,便于通过演示、源码对照与 API 查阅快速上手。

交互(Interactions)为任意 DOM 元素注入基础鼠标交互行为,短短几行代码即可组合出拖拽、缩放与列表重排,也是上层复杂控件的底层积木,包含五项核心示例:拖动(Draggable)、放置(Droppable)、缩放(Resizable)、选择(Selectable)与排序(Sortable)。本站 Chromium 实测模拟指针拖拽卡片精确位移 `(+80, +40)` 像素,点击列表项即时附加 `.ui-selected` 选中态。

小部件(Widgets)提供功能完备、具备统一核心与主题扩展能力的桌面级 Web 控件,涵盖 11 个常用组件示例:折叠面板(Accordion)、自动完成(Autocomplete)、按钮(Button)、日期选择器(Datepicker)、对话框(Dialog)、菜单(Menu)、进度条(Progressbar)、滑块(Slider)、旋转器(Spinner)、标签页(Tabs)以及工具提示框(Tooltip)。本站 Chromium 实测切换标签页将 `#tab-1` 隐藏、`#tab-2` 设为 `block`,并将进度条宽度从 `25%` 推进至 `75%`。

特效(Effects)扩展了颜色动画、CSS 类过渡与缓动曲线,并支持在元素显示隐藏或状态提示时附加丰富视觉效果,包括:特效(Effect)、可见性(Visibility:显示 Show、隐藏 Hide、切换 Toggle)、Class 动画(Class Animation:添加 Class / Add Class、移除 Class / Remove Class、切换 Class / Toggle Class、转换 Class / Switch Class)以及颜色动画(Color Animation)。本站 Chromium 实测验证元素可见性在 `none` 与 `block` 间切换,并由 `theme-a` 平滑切换为 `theme-b`。

实用工具(Utilities)是 jQuery UI 内部构建各类交互与小部件所依赖的公共设施,包含两项核心工具:用于相对锚点精准排版的定位(Position),以及用于构建有状态插件的部件库(Widget Factory)。本站 Chromium 实测将 `#pos-target` 的左上角对齐至 `#anchor` 的右下角,实测坐标精确吻合 `(502, 142)`,同时实例化徽标部件输出 `ready`。

在离线 Chromium 中联合演练交互、小部件、特效与实用工具四类示例

含完整源码 · 189 行
展开查看收起
python
"""Offline Chromium lab for jQuery UI Ch16: Examples overview (Interactions, Widgets, Effects, Utilities)."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI Examples Overview Lab</title>
<style>
  body { margin: 0; font-family: sans-serif; }
  #drag-card { position: absolute; left: 20px; top: 20px; width: 100px; height: 50px; background: #ddeeff; border: 1px solid #336699; }
  #sel-list { position: absolute; left: 20px; top: 100px; list-style: none; padding: 0; margin: 0; }
  #sel-list li { width: 100px; height: 24px; border: 1px solid #aaa; margin-bottom: 2px; }
  #sel-list li.ui-selected { background: #f39814; color: #fff; }
  #tabs { position: absolute; left: 160px; top: 20px; width: 220px; }
  .tab-panel { display: none; }
  .tab-panel.active { display: block; }
  #pb { position: absolute; left: 160px; top: 110px; width: 200px; height: 20px; border: 1px solid #666; }
  #pb-bar { height: 100%; width: 25%; background: #4caf50; }
  #fx-box { position: absolute; left: 400px; top: 20px; width: 80px; height: 40px; }
  .theme-a { background: #ccc; }
  .theme-b { background: #2196f3; color: #fff; }
  #anchor { position: absolute; left: 400px; top: 100px; width: 100px; height: 40px; border: 1px solid #333; }
  #pos-target { position: absolute; left: 0px; top: 0px; width: 60px; height: 24px; background: #ffeb3b; }
  #wf-badge { position: absolute; left: 400px; top: 180px; }
</style>
</head>
<body>
<div id="drag-card">Drag</div>
<ul id="sel-list"><li id="item-1">Item 1</li><li id="item-2">Item 2</li></ul>

<div id="tabs">
  <button id="btn-tab-1">Tab 1</button><button id="btn-tab-2">Tab 2</button>
  <div id="tab-1" class="tab-panel active">Panel 1</div>
  <div id="tab-2" class="tab-panel">Panel 2</div>
</div>

<div id="pb"><div id="pb-bar"></div></div>
<div id="fx-box" class="theme-a">FX</div>
<div id="anchor">Anchor</div>
<div id="pos-target">Target</div>
<div id="wf-badge"></div>

<script>
// 1. Draggable + Selectable interactions
(() => {
  const card = document.getElementById("drag-card");
  let dragging = false, sx = 0, sy = 0, ox = 20, oy = 20;
  card.addEventListener("mousedown", e => {
    dragging = true; sx = e.clientX; sy = e.clientY;
    ox = parseFloat(getComputedStyle(card).left);
    oy = parseFloat(getComputedStyle(card).top);
  });
  window.addEventListener("mousemove", e => {
    if (!dragging) return;
    card.style.left = (ox + e.clientX - sx) + "px";
    card.style.top = (oy + e.clientY - sy) + "px";
  });
  window.addEventListener("mouseup", () => { dragging = false; });

  document.querySelectorAll("#sel-list li").forEach(li => {
    li.addEventListener("click", () => {
      document.querySelectorAll("#sel-list li").forEach(x => x.classList.remove("ui-selected"));
      li.classList.add("ui-selected");
    });
  });
})();

// 2. Tabs + Progressbar widgets
document.getElementById("btn-tab-1").addEventListener("click", () => {
  document.getElementById("tab-1").classList.add("active");
  document.getElementById("tab-2").classList.remove("active");
});
document.getElementById("btn-tab-2").addEventListener("click", () => {
  document.getElementById("tab-2").classList.add("active");
  document.getElementById("tab-1").classList.remove("active");
});
window.setProgress = function(val) {
  const bar = document.getElementById("pb-bar");
  bar.style.width = val + "%";
  bar.dataset.value = String(val);
};

// 3. Effects: visibility + class animation helpers
window.fxOps = function() {
  const box = document.getElementById("fx-box");
  box.style.display = "none";
  const hiddenDisplay = getComputedStyle(box).display;
  box.style.display = "block";
  const shownDisplay = getComputedStyle(box).display;
  box.classList.remove("theme-a");
  box.classList.add("theme-b");
  return {
    hiddenDisplay,
    shownDisplay,
    hasThemeA: box.classList.contains("theme-a"),
    hasThemeB: box.classList.contains("theme-b")
  };
};

// 4. Utilities: Position + Widget Factory
window.runUtilities = function() {
  const anchor = document.getElementById("anchor").getBoundingClientRect();
  const target = document.getElementById("pos-target");
  // my: "left top", at: "right bottom", of: "#anchor"
  target.style.left = anchor.right + "px";
  target.style.top = anchor.bottom + "px";
  const tr = target.getBoundingClientRect();

  // Minimal widget factory instance
  const badge = document.getElementById("wf-badge");
  const widget = { options: { label: "ready" }, _create() { badge.textContent = this.options.label; } };
  widget._create();
  return {
    targetLeft: Math.round(tr.left),
    targetTop: Math.round(tr.top),
    anchorRight: Math.round(anchor.right),
    anchorBottom: Math.round(anchor.bottom),
    badgeText: badge.textContent
  };
};
</script>
</body>
</html>
"""


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)
        try:
            page = browser.new_page(viewport={"width": 800, "height": 600})
            page.set_content(HTML)

            # Case 1: Interactions (drag + select)
            before = page.locator("#drag-card").bounding_box()
            cx = before["x"] + before["width"] / 2
            cy = before["y"] + before["height"] / 2
            page.mouse.move(cx, cy)
            page.mouse.down()
            page.mouse.move(cx + 80, cy + 40, steps=4)
            page.mouse.up()
            after = page.locator("#drag-card").bounding_box()
            page.click("#item-2")
            r1 = {
                "dx": round(after["x"] - before["x"]),
                "dy": round(after["y"] - before["y"]),
                "selectedId": page.evaluate("() => document.querySelector('#sel-list li.ui-selected')?.id"),
            }
            exp1 = {"dx": 80, "dy": 40, "selectedId": "item-2"}
            cases.append(dict(name="interactions_drag_and_select_demo", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: Widgets (tabs + progressbar)
            page.click("#btn-tab-2")
            page.evaluate("() => window.setProgress(75)")
            r2 = page.evaluate("""() => ({
                tab1Display: getComputedStyle(document.getElementById('tab-1')).display,
                tab2Display: getComputedStyle(document.getElementById('tab-2')).display,
                progressWidth: document.getElementById('pb-bar').style.width
            })""")
            exp2 = {"tab1Display": "none", "tab2Display": "block", "progressWidth": "75%"}
            cases.append(dict(name="widgets_tabs_and_progressbar_demo", expected=exp2, actual=r2, passed=(r2 == exp2)))

            # Case 3: Effects (visibility + switchClass)
            r3 = page.evaluate("() => window.fxOps()")
            exp3 = {"hiddenDisplay": "none", "shownDisplay": "block", "hasThemeA": False, "hasThemeB": True}
            cases.append(dict(name="effects_class_and_visibility_demo", expected=exp3, actual=r3, passed=(r3 == exp3)))

            # Case 4: Utilities (Position + Widget Factory)
            r4 = page.evaluate("() => window.runUtilities()")
            exp4 = {"targetLeft": 502, "targetTop": 142, "anchorRight": 502, "anchorBottom": 142, "badgeText": "ready"}
            cases.append(dict(name="utilities_position_and_widget_factory_demo", expected=exp4, actual=r4, passed=(r4 == exp4)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对鼠标拖拽位移 (+80,+40) 与列表选中、Tabs 切换与 Progressbar 更新至 75%、可见性与类名转换,以及 Position 锚点对齐 (502, 142) 与 Widget Factory 初始化。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a946.zip) ↓ 查看运行说明 ↗

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

实用工具(Position、Widget Factory)处于最底层,负责统一组件构造与相对定位;交互模块提供拖拽、放置、缩放等基础鼠标行为;小部件则综合运用工具与交互提供开箱即用的完整 UI 控件。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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