Skip to content

jQuery UI 速查表

基于 jQuery 构建的用户界面交互和组件集合。

01

入门

安装与主题

jQuery UI 需要 jQuery 作为依赖。引入 CSS 主题和 JS 文件。ThemeRoller 可自定义主题。所有组件都在 DOM 元素上初始化。

jquery-ui
<!-- jQuery UI requires jQuery core first -->
<link rel="stylesheet"
      href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

文档就绪

在 $(function(){})(文档就绪)中初始化组件,确保 DOM 已存在。通过在 jQuery 集合上调用组件名称作为方法来初始化组件。选项以对象形式传入;方法通过传入方法名字符串来调用。

jquery-ui
# Install via npm
npm install jquery jquery-ui

# Import in your bundle
import $ from "jquery";
import "jquery-ui/ui/widgets/datepicker";
import "jquery-ui/themes/base/all.css";

// Or import the full bundle
import "jquery-ui";

组件方法模式

所有 jQuery UI 组件共享相同的 API:用选项初始化、通过名称字符串调用方法、通过 'option' 读写选项、用 'destroy' 销毁。'disable' 和 'enable' 切换禁用状态。这个一致的模式适用于每个组件。

jquery-ui
$(function () {
  // Initialize a widget on a selector
  $("#datepicker").datepicker();
  $("#dialog").dialog();

  // Pass options as an object
  $("#accordion").accordion({
    active: false,
    collapsible: true,
  });

  // Get or set an option after init
  $("#accordion").accordion("option", "active", 1);
});

ThemeRoller 基础

ThemeRoller(jqueryui.com/themeroller)是构建自定义 jQuery UI 主题的官方工具。它生成一个包含颜色、圆角和图标变量的 CSS 文件。CSS 框架类(ui-widget、ui-state-*、ui-corner-*)被所有组件共享,保持主题一致性。

jquery-ui
// All widgets share the same API conventions
$("#dialog").dialog("open");              // call a method
$("#dialog").dialog("option", "title");   // get an option
$("#dialog").dialog("option", "modal", true); // set an option
$("#dialog").dialog("disable");           // disable widget
$("#dialog").dialog("enable");            // enable widget
$("#dialog").dialog("widget");            // get the wrapper element
$("#dialog").dialog("destroy");           // remove widget entirely

CDN 与下载

CDN 是最快速的入门方式。生产环境中,下载构建器只打包你选择的组件,减小文件体积。使用 npm 时,可以导入单个组件模块(jquery-ui/ui/widgets/...),让打包工具 tree-shake 未使用的代码。

jquery-ui
<!-- Default base theme -->
<link rel="stylesheet"
      href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">

<!-- Other bundled themes: ui-lightness, ui-darkness, smoothness, redmond, ... -->
<link rel="stylesheet"
      href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">

<!-- Override theme with your own CSS -->
<link rel="stylesheet" href="jquery-ui.css">
<link rel="stylesheet" href="my-theme-overrides.css">

无冲突与版本检查

读取 $.ui.version 验证已加载的版本。jQuery UI 基于 jQuery 构建,所以 $.noConflict() 在全局释放 $;用 jQuery(function($){...}) 包裹代码以在局部别名 $。检查 $.ui.<组件> 可检测某组件模块是否已加载(对自定义下载构建器打包很有用)。

jquery-ui
/* jQuery UI CSS classes are namespaced with ui- */
.ui-widget         /* base widget class */
.ui-widget-header  /* header bar (accordion, datepicker) */
.ui-widget-content /* content area */
.ui-state-default  /* default interactive state */
.ui-state-hover    /* mouse-over state */
.ui-state-active   /* active/selected state */
.ui-state-focus    /* keyboard focus state */
.ui-state-disabled /* disabled state */
.ui-corner-all     /* rounded corners (themable) */
.ui-icon           /* base icon class */
02

日期选择器

基础日期选择器

Datepicker 附加到 <input>(弹出式)或 <div>/<span>(内联式)。minDate/maxDate 接受 Date 对象、数字(距今天的天数)或字符串如 '+1Y +1M'。numberOfMonths 同时显示多个月份。选中的值默认放入 input。

jquery-ui
<!-- HTML -->
<div id="box" class="ui-widget-content" style="width:100px;height:100px;">
  Drag me
</div>

<!-- JS -->
<script>
  $(function () {
    $("#box").draggable();
  });
</script>

日期格式

dateFormat 控制选中日期在输入框中的显示方式。令牌:yy=四位年份,y=两位,mm=月份(01),m=1,MM=完整月份名,dd=日(01),d=1,DD=完整星期名。使用 altField + altFormat 在隐藏 input 中存储机器可读的值(如 ISO),同时向用户显示友好格式。

jquery-ui
$("#box").draggable({
  axis: "x",              // constrain to x or y axis
  containment: "parent",  // or "window", "document", or selector
  cursor: "move",         // cursor while dragging
  cursorAt: { left: 5 },  // offset cursor from drag handle
  grid: [20, 20],         // snap to grid
  delay: 100,             // ms delay before drag starts
  distance: 5,            // px before drag starts
  revert: true,           // snap back to start
  revertDuration: 200,    // revert animation duration
  scroll: false,          // prevent auto-scroll
  helper: "clone",        // "original", "clone", or function
  opacity: 0.6,           // opacity while dragging
  zIndex: 1000,           // z-index while dragging
});

本地化 (i18n)

每个语言环境位于 i18n/datepicker-<lang>.js 文件中,填充 $.datepicker.regional[lang],包含翻译的月/日名称、dateFormat 和 firstDay。将该对象传给 datepicker() 可切换整个 UI,也可覆盖单个字符串进行精细控制。firstDay: 0 = 周日,1 = 周一。

jquery-ui
$("#box").draggable({
  start: function (event, ui) {
    console.log("Drag started", ui.position);
  },
  drag: function (event, ui) {
    // Fires continuously during drag
    console.log(ui.position.left, ui.position.top);
  },
  stop: function (event, ui) {
    console.log("Drag stopped at", ui.position);
    console.log("Offset:", ui.offset);
  },
});

最小/最大日期与禁用日期

minDate/maxDate 限定可选范围。beforeShowDay 是对每个日期单元格调用的回调;返回 [可选, 类名, 提示] 来控制某天是否可选及其外观。这是将周末、假日或业务特定禁用日期置灰的标准方法。

jquery-ui
<!-- Only the header acts as the drag handle -->
<div id="box" class="ui-widget-content">
  <div class="drag-handle">Drag from here</div>
  <div class="content">Some content here</div>
  <textarea>Editable content</textarea>
</div>

<script>
  $("#box").draggable({
    handle: ".drag-handle",   // only this starts the drag
    cancel: "textarea",       // these elements never start a drag
  });
</script>

月份与年份下拉框

changeMonth 和 changeYear 添加下拉框,用户可以直接跳转年份而无需逐月翻页。yearRange 限制下拉框的年份范围(绝对值 '2020:2030' 或相对值 '-10:+10')。showButtonPanel 在日历底部显示 Today 和 Done 按钮。

jquery-ui
// Constrain within a parent element
$("#box").draggable({ containment: "parent" });

// Constrain within the window
$("#box").draggable({ containment: "window" });

// Constrain within a specific selector
$("#box").draggable({ containment: "#drag-area" });

// Constrain to an explicit bounding box [x1, y1, x2, y2]
$("#box").draggable({ containment: [0, 0, 500, 300] });

// Snap to a 50px grid
$("#box").draggable({ grid: [50, 50] });

事件与方法

onSelect 在用户选择某天时触发;onClose 在弹出框关闭时触发(无论是否有选择);onChangeMonthYear 在用户切换月份时触发。getDate 返回 JS Date;setDate 接受 Date、数字或字符串。show/hide 以编程方式控制弹出框。

jquery-ui
$(".card").draggable({
  snap: ".snap-target",     // selector of elements to snap to
  snapMode: "inner",        // "inner", "outer", or "both"
  snapTolerance: 30,        // px distance to trigger snap
});

// Snap to all siblings of the same class
$(".card").draggable({
  snap: ".card",
  snapTolerance: 20,
});
03

自动完成

基础自动完成

Autocomplete 在用户输入时建议匹配项。source 是数据源:字符串数组、{label, value} 对象数组(label 显示在菜单中,value 插入输入框)、URL 字符串(服务端过滤)或函数。当 source 是本地数组时,菜单默认在客户端过滤。

jquery-ui
<div id="draggable" class="ui-widget-content">Drag me</div>
<div id="droppable" class="ui-widget-header">Drop here</div>

<script>
  $(function () {
    $("#draggable").draggable();
    $("#droppable").droppable({
      drop: function (event, ui) {
        $(this).addClass("ui-state-highlight")
               .html("Dropped!");
      },
    });
  });
</script>

远程数据源 (AJAX)

对于大型数据集,在服务端过滤。source 函数接收 request(其中 request.term = 当前输入)和 response 回调。异步获取匹配项并传给 response。minLength 避免过早请求;delay 对输入去抖以减少服务器负载。

jquery-ui
$("#droppable").droppable({
  accept: ".special",       // only accept matching draggables
  activeClass: "ui-state-default",  // class while a drag is active
  hoverClass: "ui-state-hover",     // class while draggable is over
  tolerance: "fit",         // drop detection mode
  greedy: true,             // stop event propagation
  disabled: false,          // disable the droppable
});

自定义数据与 renderItem

覆盖实例的 _renderItem 可完全控制每个菜单行的 HTML —— 适用于富结果(头像、描述、徽章)。默认插入 item.label。手动设置输入值时务必从 select/focus 返回 false,防止组件覆盖它。通过 .autocomplete('instance') 访问实例。

jquery-ui
$("#droppable").droppable({
  activate: function (event, ui) {
    // Fires when an accepted draggable starts moving
    $(this).addClass("ui-state-default");
  },
  deactivate: function (event, ui) {
    // Fires when the drag ends (drop or cancel)
    $(this).removeClass("ui-state-default");
  },
  over: function (event, ui) {
    // Draggable entered the drop zone
    $(this).addClass("ui-state-hover");
  },
  out: function (event, ui) {
    // Draggable left the drop zone
    $(this).removeClass("ui-state-hover");
  },
  drop: function (event, ui) {
    // Draggable was released here
    console.log("Dropped:", ui.draggable);
  },
});

分类

官方 Categories 示例通过 $.widget 扩展 autocomplete,覆盖 _renderMenu 将结果按分类标题分组。先按分类排序项目,使标题只出现一次。_renderItemData 渲染普通行;只需在分类变化时注入标题 <li>。

jquery-ui
<!-- HTML: red and blue boxes -->
<div class="red draggable">Red</div>
<div class="blue draggable">Blue</div>

<div id="red-bin" class="bin">Red bin</div>
<div id="blue-bin" class="bin">Blue bin</div>

<script>
  // Only accept elements matching the selector
  $("#red-bin").droppable({ accept: ".red" });
  $("#blue-bin").droppable({ accept: ".blue" });

  // Or use a function for dynamic logic
  $("#any-bin").droppable({
    accept: function (drag) {
      return $(drag).data("category") === "recyclable";
    },
  });
</script>

多值输入

此多值模式(来自官方示例)允许用户在一个输入框中添加多个标签。每次选择时,将最后一个部分词替换为选中的值,并重新添加一个空词以继续输入。$.ui.autocomplete.filter 执行客户端匹配;keyCode.TAB 处理防止组件在输入过程中抢走焦点。

jquery-ui
$("#droppable").droppable({
  // "fit": draggable must be fully inside (default)
  tolerance: "fit",

  // "intersect": at least 50% overlap
  tolerance: "intersect",

  // "pointer": mouse pointer must be inside
  tolerance: "pointer",

  // "touch": any edge touching counts
  tolerance: "touch",
});

组合框 (Select + Autocomplete)

Combobox 组件(官方示例)用文本输入框包装原生 <select>,用户可以输入过滤或从下拉框中选择 —— 结合了 select 的选项与 autocomplete 的自由输入。这是一个起点:扩展 _createShowAllButton 和 _destroy 以满足需求。无障碍优先时建议使用原生 <select>。

jquery-ui
<!-- CSS -->
<style>
  .drop-active { border: 2px dashed #ccc; }
  .drop-hover  { border: 2px solid #0a0; background: #efe; }
</style>

<!-- JS -->
$("#zone").droppable({
  accept: ".item",
  activeClass: "drop-active",
  hoverClass: "drop-hover",
  drop: function (event, ui) {
    $(this).append(ui.draggable);
    ui.draggable.css({ top: 0, left: 0 });
  },
});
04

标签页

基础标签页

标记模式是一个 <ul> 中的 <li><a href='#panel-id'> 链接与共享这些 id 的内容面板配对。tabs() 连接链接来显示/隐藏面板并添加 ARIA 角色以支持无障碍。点击标签页切换面板;活动标签页获得 ui-tabs-active 类。

jquery-ui
<div id="box" class="ui-widget-content">
  Resize me from the corner
</div>

<script>
  $(function () {
    $("#box").resizable();
  });
</script>

AJAX 标签页

当 <a href> 指向 URL(非 #id)时,tabs 在首次激活时通过 AJAX 将该 URL 加载到面板中。beforeLoad 允许你拦截 jqXHR(用于错误处理或缓存)。默认每个标签页只加载一次并缓存;如需每次重新加载,在 beforeLoad 中中止并自行管理。

jquery-ui
$("#box").resizable({
  handles: "n, e, s, w, ne, se, sw, nw",  // all eight handles
});

// Or specify handle elements
$("#box").resizable({
  handles: {
    n: ".n-handle",
    se: ".se-handle",
  },
});

可折叠与活动控制

active 设置初始打开的标签页;collapsible:true 时点击活动标签页可折叠(所有面板关闭)。disabled 接受标签页索引数组。event 更改触发方式(如 mouseover),但 click 最具无障碍性。方法允许以编程方式切换、禁用或查询活动标签页。

jquery-ui
$("#box").resizable({
  alsoResize: "#other",     // resize another element in sync
  animate: true,            // animate to final size
  animateDuration: 200,     // ms
  aspectRatio: 16 / 9,      // preserve width:height ratio
  autoHide: true,           // hide handles until hover
  containment: "parent",    // restrict resize within parent
  grid: [10, 10],           // snap to grid
  maxHeight: 400,
  maxWidth: 600,
  minHeight: 100,
  minWidth: 100,
  ghost: true,              // show a ghost outline while resizing
});

可排序标签页

用 sortable({ axis: 'x' }) 包装标签页导航(.ui-tabs-nav),用户可以拖动标签页重新排序。排序结束后调用 tabs('refresh') 让组件重新读取新的标签页顺序。如需持久化顺序,可结合 cookies/localStorage。

jquery-ui
$("#box").resizable({
  start: function (event, ui) {
    console.log("Resize start", ui.size, ui.position);
  },
  resize: function (event, ui) {
    // Fires continuously during resize
    ui.size.width;   // new width
    ui.size.height;  // new height
    ui.position.left; // new position (may change for n/w handles)
  },
  stop: function (event, ui) {
    console.log("Final size:", ui.size);
  },
});

标签页事件

beforeActivate 在标签页切换前触发(返回 false 可阻止);activate 在切换后触发,提供 ui.newTab/newPanel 和 ui.oldTab/oldPanel。beforeLoad/load 包装远程标签页的 AJAX 生命周期。这些钩子用于验证、懒加载或面板过渡动画。

jquery-ui
// Keep a 4:3 ratio
$("#photo").resizable({ aspectRatio: 4 / 3 });

// Keep ratio and stay within bounds
$("#photo").resizable({
  aspectRatio: 4 / 3,
  maxWidth: 800,
  maxHeight: 600,
  minWidth: 100,
  minHeight: 75,
});

// Snap to a grid of 20px
$("#grid-box").resizable({ grid: [20, 20] });

标签页方法与刷新

tabs('refresh') 重新扫描 DOM,可在运行时添加/删除标签页 —— 在更改标记后调用它。load(idx) 强制重新加载 AJAX 标签页。destroy 移除组件并恢复原始 HTML。关闭图标模式是经典的'可关闭标签页'示例。

jquery-ui
// Animate to the final size after release
$("#box").resizable({
  animate: true,
  animateDuration: "slow",   // or ms number
  animateEasing: "swing",
});

// Show a ghost outline while dragging, apply on release
$("#box").resizable({
  ghost: true,
  helper: "ui-resizable-helper",  // class for the ghost
});

// Combine both
$("#box").resizable({ ghost: true, animate: true });
05

手风琴

基础手风琴

手风琴期望成对的标题 + 内容元素(默认:h3 标题,div 面板)。一次只有一个部分打开;打开一个会关闭其他。标题元素可通过 header 选项配置(如 'h2' 或类名)。

jquery-ui
<ol id="selectable">
  <li class="ui-widget-content">Item 1</li>
  <li class="ui-widget-content">Item 2</li>
  <li class="ui-widget-content">Item 3</li>
</ol>

<script>
  $(function () {
    $("#selectable").selectable();
  });
</script>

可折叠模式

默认点击打开的标题不做任何事 —— 它保持打开。collapsible:true 允许关闭它,使所有部分都折叠。jQuery UI 的手风琴严格只开一个;如需多开行为,可手动构建 slideToggle 模式或使用多个独立的手风琴实例。

jquery-ui
$("#selectable").selectable({
  filter: "li",            // which children can be selected
  tolerance: "touch",      // "touch" or "fit" for lasso overlap
  distance: 0,             // px before lasso starts
  delay: 0,                // ms delay before lasso starts
  autoRefresh: true,       // recompute positions on each drag
  disabled: false,
  cancel: "a, .no-select", // elements that never start selection
});

活动控制

active 设置初始打开的部分(索引,或与 collapsible 配合使用 false)。animate 控制滑动持续时间/缓动(false 禁用)。refresh 在运行时添加或删除部分后重新计算高度/标题 —— 对动态手风琴必不可少。

jquery-ui
$("#selectable").selectable({
  selecting: function (event, ui) {
    // ui.selecting: element being lassoed
    $(ui.selecting).addClass("highlight");
  },
  selected: function (event, ui) {
    // ui.selected: element just confirmed selected
    console.log("Selected:", $(ui.selected).text());
  },
  unselecting: function (event, ui) {
    $(ui.unselecting).removeClass("highlight");
  },
  unselected: function (event, ui) {
    console.log("Unselected:", $(ui.unselected).text());
  },
  start: function (event, ui) { /* lasso started */ },
  stop: function (event, ui) { /* lasso released */ },
});

高度样式

heightStyle:'auto' 将所有面板设为最高面板的高度(切换时跳动);'fill' 填充父容器并滚动溢出;'content' 让每个面板保持自然高度(过渡最平滑)。'fill' 要求手风琴有定义的高度。

jquery-ui
<ul id="gallery">
  <li class="selectable-item">Photo 1</li>
  <li class="locked">Locked</li>
  <li class="selectable-item">Photo 2</li>
</ul>

<script>
  $("#gallery").selectable({
    filter: ".selectable-item",  // only these can be selected
    cancel: ".locked",            // locked items never select
  });
</script>

图标与标题

header 允许使用任何选择器(h2、类名等)替代 h3。icons 将关闭(header)和打开(activeHeader)状态映射到 jQuery UI 图标类。设置 icons:false 可取消箭头。图标类来自主题的图标精灵图。

jquery-ui
/* CSS */
#selectable .ui-selecting {
  background: #feca40;        /* while dragging */
}
#selectable .ui-selected {
  background: #f39814;        /* confirmed selection */
  color: white;
}
#selectable li {
  margin: 3px; padding: 6px;
  border: 1px solid #ccc;
}

/* selected count badge */
function updateCount() {
  var n = $("#selectable .ui-selected").length;
  $("#count").text(n + " selected");
}
$("#selectable").on("selectablestop", updateCount);

手风琴事件

beforeActivate 在面板打开/关闭前触发(返回 false 可阻止);activate 在之后触发,提供 ui.newHeader/newPanel 和 ui.oldHeader/oldPanel。用于懒加载内容到刚打开的面板、验证或触发布局重新计算。

jquery-ui
// Refresh positions after DOM changes
$("#selectable").selectable("refresh");

// Disable / enable
$("#selectable").selectable("disable");
$("#selectable").selectable("enable");

// Remove the widget
$("#selectable").selectable("destroy");

// Manually select an item (set the class)
$("#selectable li").eq(2).addClass("ui-selected");

// Clear all selections
$("#selectable .ui-selected").removeClass("ui-selected");
06

对话框

基础对话框

Dialog 将 div 转换为浮动窗口,带有标题栏(来自 title 属性)、关闭按钮和可配置按钮。autoOpen:true 立即打开;设为 false 则稍后调用 dialog('open')。buttons 数组是现代形式(包含 text 和 click 的对象)—— 优于旧版键值映射。

jquery-ui
<ul id="sortable">
  <li class="ui-widget-content">Item 1</li>
  <li class="ui-widget-content">Item 2</li>
  <li class="ui-widget-content">Item 3</li>
</ul>

<script>
  $(function () {
    $("#sortable").sortable();
  });
</script>

模态对话框

modal:true 使页面变暗并阻止与对话框后面元素的交互 —— 对确认和表单至关重要。draggable/resizable 默认开启。show/hide 接受效果对象用于打开/关闭动画。closeOnEscape 允许 Esc 键关闭对话框。

jquery-ui
$("#sortable").sortable({
  axis: "y",                // constrain to vertical
  cursor: "move",
  handle: ".handle",        // drag from this element only
  placeholder: "sortable-placeholder", // class for the drop preview
  forcePlaceholderSize: true, // match placeholder to item size
  helper: "clone",          // "original" or "clone"
  opacity: 0.7,
  revert: true,             // animate item into place
  tolerance: "pointer",     // "intersect" or "pointer"
  scroll: true,             // auto-scroll the page
  containment: "parent",    // restrict within parent
});

对话框按钮

buttons 数组形式支持每按钮图标,并允许轻松重排/重命名。在 click 处理函数内,'this' 是对话框元素,所以 $(this).dialog('close') 可关闭它。通过 dialog('option', 'buttons', [...]) 在运行时更改按钮。框架自动添加正确的 ARIA 角色以支持无障碍。

jquery-ui
$("#sortable").sortable({
  start: function (event, ui) {
    ui.item;            // the dragged element
    ui.placeholder;     // the placeholder element
    ui.helper;          // the helper being dragged
  },
  change: function (event, ui) {
    // Position in list changed during drag
  },
  sort: function (event, ui) {
    // Fires continuously while sorting
  },
  beforeStop: function (event, ui) {
    // Just before the item is placed
  },
  stop: function (event, ui) {
    console.log("Sort ended");
  },
  update: function (event, ui) {
    // Order actually changed — persist it here
    var order = $(this).sortable("toArray");
    saveOrder(order);
  },
});

对话框中的表单

常见模式:在模态对话框中放置表单,在主按钮上验证,通过 AJAX 提交,并在 close 处理函数中重置表单,使重新打开时显示干净状态。用 dialog('open') 打开;通过按钮或 Esc 关闭。

jquery-ui
<ul id="list-a" class="connected">
  <li>Task A1</li><li>Task A2</li>
</ul>
<ul id="list-b" class="connected">
  <li>Task B1</li>
</ul>

<script>
  $(".connected").sortable({
    connectWith: ".connected",  // allow moving between lists
    placeholder: "ui-state-highlight",
  }).disableSelection();
</script>

定位与动画

position 使用与 Position 工具相同的语法:my(对话框的哪条边)对齐到 at(目标 'of' 元素的哪条边)。默认在窗口中居中。show/hide 接受任何 jQuery UI 效果(blind、explode、fade、slide、drop、puff、scale...)。动态内容后重新设置 position 以保持居中。

jquery-ui
$("#sortable").sortable({
  placeholder: "ui-state-highlight",  // class for the gap
  forcePlaceholderSize: true,
  helper: function (event, el) {
    // Return a custom helper element
    return $("<div class='custom-helper'>Moving...</div>");
  },
  cursorAt: { top: 10, left: 10 },
});

// Use a clone as the helper instead of moving the original
$("#sortable").sortable({ helper: "clone" });

对话框方法与事件

open/close 切换可见性;moveToTop 将对话框提升到同栈的其他对话框之上;isOpen 查询状态。beforeClose 返回 false 可阻止关闭(适合'未保存更改'保护)。dragStop/resizeStop 在用户交互完成后触发。

jquery-ui
// Get current order as an array of IDs
var order = $("#sortable").sortable("toArray");
// ["item-1", "item-3", "item-2"]

// Get option values
var placeholder = $("#sortable").sortable("option", "placeholder");

// Serialize items as a query string (uses id="name_number")
var data = $("#sortable").sortable("serialize");
// "item[]=1&item[]=2&item[]=3"

// Cancel the current sort (revert)
$("#sortable").sortable("cancel");

// Refresh positions after DOM changes
$("#sortable").sortable("refresh");

// Disable / enable / destroy
$("#sortable").sortable("disable");
$("#sortable").sortable("enable");
$("#sortable").sortable("destroy");
07

按钮与按钮组

基础按钮

button() 为 <button>、<a> 和 <input type=submit/button/reset> 增添主题外观和悬停/激活状态。<a> 按钮适用于非表单操作。button() 用于单个元素;buttonset() 用于分组单选/复选框。

jquery-ui
<div id="accordion">
  <h3>Section 1</h3>
  <div>Content for section 1</div>
  <h3>Section 2</h3>
  <div>Content for section 2</div>
  <h3>Section 3</h3>
  <div>Content for section 3</div>
</div>

<script>
  $(function () {
    $("#accordion").accordion();
  });
</script>

带图标的按钮

icon 添加主题图标(1.12+ 默认在左侧;使用 iconPosition 定位)。showLabel:false 创建纯图标按钮 —— 务必设置 label 以支持无障碍(屏幕阅读器 + title)。图标来自主题精灵图(ui-icon-<名称>)。

jquery-ui
$("#accordion").accordion({
  active: 0,                 // index of open panel (false = all closed)
  collapsible: true,         // allow closing all panels
  disabled: false,
  animate: 200,              // ms or "ease name" or false
  heightStyle: "content",    // "auto", "fill", or "content"
  header: "h3",              // header selector
  icons: {
    header: "ui-icon-triangle-1-e",
    activeHeader: "ui-icon-triangle-1-s",
  },
  event: "click",            // event that toggles panels
});

按钮组 (单选组)

buttonset() 将共享 name 的一组单选框(或复选框)样式化为连接的分段控件。底层 input 仍持有值,所以用 .prop('checked') 读写,并在更改的 input 上调用 button('refresh') 更新其视觉状态。

jquery-ui
$("#accordion").accordion({
  beforeActivate: function (event, ui) {
    // ui.oldHeader, ui.oldPanel (closing)
    // ui.newHeader, ui.newPanel (opening)
    // Return false to cancel
    if ($(ui.newHeader).data("locked")) return false;
  },
  activate: function (event, ui) {
    // Fires after a panel finishes opening
    console.log("Opened:", ui.newHeader.text());
  },
  create: function (event, ui) {
    // Fires on initialization
    console.log("Accordion created, open:", ui.header.text());
  },
});

复选框按钮

buttonset() 也适用于复选框,用于多切换工具栏。用 .prop('checked') 跟踪状态。以编程方式切换后,调用 button('refresh')(或刷新整个组)以同步按下外观。

jquery-ui
$("#accordion").accordion({
  icons: {
    header: "ui-icon-circle-arrow-e",
    activeHeader: "ui-icon-circle-arrow-s",
  },
});

// Disable icons entirely
$("#accordion").accordion({ icons: false });

// Use your own icon classes (e.g. with FontAwesome)
$("#accordion").accordion({
  icons: {
    header: "fa fa-plus",
    activeHeader: "fa fa-minus",
  },
});

分裂按钮

jQuery UI 没有内置分裂按钮 —— 常见配方是组合两个按钮(主按钮 + 箭头)和 menu 组件。点击箭头在其下方打开菜单;选择一项执行替代操作。使用 menu 组件作为下拉项。

jquery-ui
// Allow all panels to be closed
$("#accordion").accordion({
  collapsible: true,
  active: false,   // start with all closed
});

// Make every section independently toggleable
// (a true multi-open accordion = separate collapsibles)
$(".section").each(function () {
  $(this).accordion({
    collapsible: true,
    active: false,
    header: ".section-header",
  });
});

按钮方法与事件

disable/enable 切换禁用状态并添加正确的 ARIA。refresh 在通过 jQuery 更改元素状态(选中/禁用/标签)后重新读取 —— 每当修改源 input 时都要调用。Button 本身不发自定义事件;在底层元素上绑定 click/change。

jquery-ui
// Refresh after adding content
$("#accordion").append("<h3>New</h3><div>Content</div>");
$("#accordion").accordion("refresh");

// Switch the open panel
$("#accordion").accordion("option", "active", 2);

// Disable / enable
$("#accordion").accordion("disable");
$("#accordion").accordion("enable");

// Destroy
$("#accordion").accordion("destroy");

// Load content on demand (AJAX-style)
$("#accordion").accordion({
  beforeActivate: function (event, ui) {
    var panel = ui.newPanel;
    if (panel.is(":empty")) {
      panel.load("/api/section/" + ui.newHeader.data("id"));
    }
  },
});
08

菜单

基础菜单

Menu 将嵌套 <ul> 转换为可键盘导航的菜单,支持子菜单。每个项是包含 <div>(或 <a>)标签的 <li>;嵌套 <ul> 成为在悬停/箭头时打开的子菜单。组件处理箭头键导航、ARIA 角色和自动聚焦。

jquery-ui
<label for="city">City:</label>
<input id="city" type="text">

<script>
  $(function () {
    var cities = ["London", "Paris", "Berlin", "Madrid", "Rome"];
    $("#city").autocomplete({ source: cities });
  });
</script>

带图标与禁用的菜单

在项的 div 内放置带主题的 span.ui-icon 可添加图标。添加 ui-state-disabled 类可禁用项(键盘/鼠标会忽略)。仅包含短横线 '-' 的 <li> 渲染为分隔符。这些是组件自动识别的标记约定。

jquery-ui
$("#city").autocomplete({
  source: "/api/cities",   // server endpoint
  minLength: 2,            // start suggesting after 2 chars
  delay: 300,              // ms between keystroke and request
});

// The server should return JSON like:
// ["London", "Paris", "Berlin"]
// or [{ "label": "London, UK", "value": "London" }]

子菜单与定位

position 控制每个子菜单相对于其父项出现的位置,使用 Position 工具语法。默认向右打开;'collision: flip' 在空间不足时镜像翻转 —— 对靠近视口右边缘的菜单必不可少。delay 避免鼠标经过时意外打开子菜单。

jquery-ui
$("#city").autocomplete({
  source: cities,          // array, URL, or function
  minLength: 1,            // chars before suggestions appear
  delay: 300,              // ms between keystroke and request
  autoFocus: true,         // focus first item automatically
  appendTo: "#container",  // where to render the menu
  position: { my: "left top", at: "left bottom" },
  disabled: false,
});

菜单方法

编程导航方法(next/previous/first/last/expand/collapse)镜像键盘行为,适用于测试或自定义键盘处理。focus(null, item) 设置活动项;refresh 在动态添加/删除项后重建。

jquery-ui
$("#city").autocomplete({
  source: function (request, response) {
    // request.term is the typed text
    // response() must be called with the results array
    $.getJSON("/api/cities", { q: request.term })
      .done(function (data) {
        response(data);
      })
      .fail(function () {
        response([]);  // always call response, even on error
      });
  },
  select: function (event, ui) {
    // ui.item.label, ui.item.value
    $("#city-id").val(ui.item.id);
  },
});

菜单事件

select 在用户选择项时触发(点击或 Enter);ui.item 是选中的 <li>。focus/blur 跟踪哪个项被高亮(鼠标悬停或键盘)。在 select 中编写业务逻辑 —— 它相当于菜单项的点击处理函数。

jquery-ui
$("#city").autocomplete({
  source: cities,
  focus: function (event, ui) {
    // Fires when an item is highlighted (not selected)
    $("#preview").text(ui.item.label);
    return false;  // prevent setting the input value on focus
  },
  select: function (event, ui) {
    // Fires when an item is chosen
    $("#city").val(ui.item.label);
    $("#city-id").val(ui.item.value);
    return false;  // prevent default behavior
  },
  change: function (event, ui) {
    // Fires when input loses focus
    if (!ui.item) {
      // User typed something not in the list
      console.log("No match:", this.value);
    }
  },
});

Categories & Custom Rendering

Override _renderMenu or _renderItem to customize the dropdown layout. This example groups suggestions by category with header rows. The $.widget pattern extends the base autocomplete, so all original options and events still work. Common for search interfaces.

jquery-ui
$.widget("custom.catcomplete", $.ui.autocomplete, {
  _renderMenu: function (ul, items) {
    var that = this, currentCategory = "";
    $.each(items, function (index, item) {
      if (item.category !== currentCategory) {
        ul.append("<li class='ui-autocomplete-category'>"
          + item.category + "</li>");
        currentCategory = item.category;
      }
      that._renderItemData(ul, item);
    });
  },
});

// Use the new widget
$("#search").catcomplete({
  source: [
    { label: "Java", category: "Languages" },
    { label: "JavaScript", category: "Languages" },
    { label: "React", category: "Frameworks" },
  ],
});
09

进度条

基础进度条

Progressbar 显示确定的 0-100 百分比填充。value 设置当前百分比(0-100)。组件更新内部 .ui-progressbar-value div 的宽度。不传第二参数读取值;传入数字设置值。

jquery-ui
<!-- Apply to button, input, or anchor elements -->
<button id="btn">Click me</button>
<input type="submit" id="submit" value="Submit">
<a href="#" id="link" class="btn">Link button</a>

<script>
  $(function () {
    $("#btn").button();
    $("#submit").button();
    $("#link").button();
  });
</script>

不确定进度条

value:false 将进度条置于不确定模式 —— 带动画条纹但无特定完成度,在任务长度未知时使用(如等待服务器)。一旦可以衡量进度就切换为数值。

jquery-ui
$("#btn").button({
  disabled: false,
  text: true,              // show the label text
  icon: "ui-icon-gear",    // primary icon class
  iconPosition: "beginning", // "beginning" or "end"
  showLabel: true,         // text or icon only
  label: "Save",           // override the button's text
});

// Icon-only button (must set showLabel: false)
$("#icon-btn").button({
  icon: "ui-icon-disk",
  showLabel: false,
});

自定义标签与动画

在进度条内叠加一个 label div 并随值更新。经典示例使用 setInterval 循环模拟进度;在实际应用中从上传进度事件、服务器轮询或 WebSocket 消息驱动 update()。设置 max 用于非 100 进制。

jquery-ui
<div id="size-set">
  <input type="radio" id="s1" name="size"><label for="s1">S</label>
  <input type="radio" id="s2" name="size" checked><label for="s2">M</label>
  <input type="radio" id="s3" name="size"><label for="s3">L</label>
</div>

<script>
  $("#size-set").buttonset();

  // For checkboxes (multi-select):
  // $("#check-set").controlgroup();  // 1.12+
</script>

进度条方法与最大值

max 更改进制(默认 100)。value 以 max 单位计,不是百分比,所以 max 为 250 时 value 100 是 40%。组件不会为你重新标注 —— max 不同时自行计算显示百分比。disable 置灰进度条;destroy 移除组件。

jquery-ui
// Primary icon
$("#save").button({ icon: "ui-icon-disk" });

// Icon only (no text)
$("#play").button({
  icon: "ui-icon-play",
  showLabel: false,
});

// Change icon at runtime
$("#play").button("option", "icon", "ui-icon-pause");

// Available icons include:
// ui-icon-gear, ui-icon-disk, ui-icon-trash,
// ui-icon-search, ui-icon-close, ui-icon-check,
// ui-icon-arrowthick-1-n/e/s/w, and many more

进度条事件

change 在值变化时触发(包括编程更新);complete 在值达到 max 时触发。用 complete 推进到下一步(关闭模态、重定向、显示成功)。两者都以 'this' 作为进度条元素。

jquery-ui
<div class="toolbar">
  <button id="save">Save</button>
  <button id="save-arrow"><span class="ui-icon ui-icon-triangle-1-s"></span></button>
</div>

<script>
  $("#save").button();
  $("#save-arrow").button({ text: false, icon: "ui-icon-triangle-1-s" });

  $("#save-arrow").on("click", function () {
    $("#menu").menu("widget").show();
  });
</script>

<!-- Combine with a Menu for a true split button -->
<ul id="menu" style="display:none;">
  <li><div>Save</div></li>
  <li><div>Save As...</div></li>
  <li><div>Export</div></li>
</ul>

Button Methods

Use the option method to change label, icon, or disabled state at runtime — typical for stateful buttons like 'Submit' → 'Loading...'. The refresh method re-reads the element's state (useful for checkboxes toggled programmatically). destroy removes all styling.

jquery-ui
// Disable / enable
$("#btn").button("disable");
$("#btn").button("enable");

// Change options
$("#btn").button("option", "label", "Loading...");
$("#btn").button("option", "disabled", true);

// Get the button element
$("#btn").button("widget");

// Refresh after DOM changes (e.g. removing a class)
$("#btn").button("refresh");

// Remove the widget
$("#btn").button("destroy");
10

选择菜单

基础选择菜单

selectmenu() 用带主题、支持无障碍的下拉框替换原生 <select>,同时保持底层 <select> 同步(表单仍可正确提交)。width 通常需要显式设置,因为样式化组件不像原生控件那样自动调整大小。

jquery-ui
<label for="date">Pick a date:</label>
<input type="text" id="date">

<script>
  $(function () {
    $("#date").datepicker();
  });
</script>

自定义渲染

覆盖菜单的 _renderItem(通过 selectmenu('menuWidget').menu('instance') 访问)可为每个选项添加图标、描述或样式化徽章。item.element 是原始 <option>,所以 .data() 可附加每选项元数据。底层值仍正常提交。

jquery-ui
$("#date").datepicker({
  dateFormat: "yy-mm-dd",     // ISO format
  defaultDate: "+1",          // tomorrow when calendar opens
  minDate: 0,                 // no past dates (today+)
  maxDate: "+1Y",             // up to one year ahead
  numberOfMonths: 2,          // show 2 months side by side
  showButtonPanel: true,      // Today/Done buttons
  changeMonth: true,          // dropdown for month
  changeYear: true,           // dropdown for year
  showAnim: "fadeIn",         // open animation
  duration: "fast",
  firstDay: 1,                // start week on Monday
  showWeek: true,             // show week numbers
});

禁用选项与选项组

selectmenu 尊重 <optgroup>(渲染为不可选的组标题)和 disabled <option>(置灰、不可点击)。用 disable/enable 禁用整个组件。组件镜像原生语义,可作为 <select> 的直接替换。

jquery-ui
$("#date").datepicker({
  dateFormat: "yy-mm-dd",  // 2026-07-04
});

// Format tokens:
// d  - day of month, no leading zero (1)
// dd - day, two digits (01)
// D  - short day name (Mon)
// DD - full day name (Monday)
// m  - month, no leading zero (1)
// mm - month, two digits (01)
// M  - short month name (Jan)
// MM - full month name (January)
// y  - two-digit year (26)
// yy - four-digit year (2026)
// @  - Unix timestamp
// ! - Windows ticks

// Common formats:
// "mm/dd/yy"      -> 07/04/2026
// "yy-mm-dd"      -> 2026-07-04
// "DD, MM d, yy"  -> Friday, July 4, 2026

选择菜单方法

open/close 以编程方式切换下拉框。value('Fast') 选择值为 'Fast' 的选项;不传参数读取。添加/删除/修改 <option> 元素后调用 refresh 使样式化菜单反映更改。destroy 恢复原生 <select>。

jquery-ui
// Restrict to a date range
$("#start").datepicker({
  minDate: 0,
  maxDate: "+6M",
  onSelect: function (dateText) {
    // Set the end date's minimum to the start date
    $("#end").datepicker("option", "minDate", dateText);
  },
});
$("#end").datepicker({
  minDate: 0,
  maxDate: "+6M",
  onSelect: function (dateText) {
    $("#start").datepicker("option", "maxDate", dateText);
  },
});

// Disable weekends
$("#date").datepicker({
  beforeShowDay: $.datepicker.noWeekends,
});

选择菜单事件

change 是主要事件 —— 在用户选择不同选项时触发,ui.item 持有选中的 {value, label, element}。select 在每次选择时触发(即使未更改)。open/close/focus 支持 UI 反馈(如懒加载选项列表)。

jquery-ui
// Set the regionalization
$("#date").datepicker($.datepicker.regional["fr"]);

// Override specific strings
$("#date").datepicker({
  monthNames: ["janvier","février","mars","avril","mai","juin",
               "juillet","août","septembre","octobre","novembre","décembre"],
  dayNamesMin: ["Di","Lu","Ma","Me","Je","Ve","Sa"],
  firstDay: 1,
  dateFormat: "dd/mm/yy",
  prevText: "Précédent",
  nextText: "Suivant",
  closeText: "Fermer",
  currentText: "Aujourd'hui",
});

// Include the regional file for built-in locales:
// <script src="jquery-ui/i18n/datepicker-fr.js"></script>

Inline Datepicker & Events

Apply datepicker to a div instead of an input for an always-visible inline calendar — great for booking interfaces. onSelect fires when a date is picked, onChangeMonthYear when navigating months. getDate/setDate work with Date objects for programmatic control.

jquery-ui
<!-- Inline (always visible) calendar -->
<div id="inline-calendar"></div>

<script>
  $("#inline-calendar").datepicker({
    onSelect: function (dateText, inst) {
      console.log("Selected:", dateText);
    },
    onChangeMonthYear: function (year, month, inst) {
      console.log("Viewing:", month + "/" + year);
    },
    beforeShow: function (input, inst) {
      // Fires before the popup opens
      return { /* override options */ };
    },
    onClose: function (dateText, inst) {
      // Fires when the popup closes
    },
  });

  // Methods
  $("#date").datepicker("setDate", "+7");  // set to a week from today
  $("#date").datepicker("getDate");        // returns a Date object
  $("#date").datepicker("option", "minDate", new Date(2026, 0, 1));
</script>
11

滑块

基础滑块

Slider 在轨道上创建可拖动的手柄。min/max 定义范围,value 初始位置,step 步长。slide 回调在用户拖动时持续触发 —— 用它更新实时标签。手柄的值在 ui.value 中。

jquery-ui
<div id="dialog" title="Basic dialog">
  <p>This is a simple dialog window.</p>
</div>

<script>
  $(function () {
    $("#dialog").dialog();
  });
</script>

范围滑块

range:true 配合 values:[a,b] 创建双柄滑块,两柄之间有填充段 —— 非常适合价格/年龄范围筛选。从 ui.values(数组)读取两个值。range:'min' 或 'max' 则从单柄向端点着色。

jquery-ui
$("#dialog").dialog({
  autoOpen: false,           // don't open on init
  modal: true,               // dim the page behind
  width: 400,
  height: "auto",
  minWidth: 200,
  maxWidth: 600,
  resizable: true,
  draggable: true,
  closeOnEscape: true,
  position: { my: "center", at: "center", of: window },
  title: "Custom Title",     // override the title attr
  show: { effect: "fade", duration: 200 },
  hide: { effect: "fade", duration: 200 },
});

步长、最小值、最大值

step 将手柄量化为倍数(整数或小数)。min/max 限定范围。范围滑块使用 values(复数)—— values() 读取,values(idx, val) 或 values([a,b]) 设置。重新设置选项会自动重新计算手柄位置。

jquery-ui
$("#dialog").dialog({
  buttons: [
    {
      text: "Save",
      icon: "ui-icon-disk",
      click: function () {
        saveForm();
        $(this).dialog("close");
      },
    },
    {
      text: "Cancel",
      click: function () {
        $(this).dialog("close");
      },
    },
  ],
});

// Shortcut object form (1.12+)
$("#dialog").dialog({
  buttons: {
    "Save": function () { saveForm(); $(this).dialog("close"); },
    "Cancel": function () { $(this).dialog("close"); },
  },
});

垂直滑块

orientation:'vertical' 渲染垂直滑块。CSS height 必须为垂直滑块显式设置(不会自动调整大小)。值仍从 min 到 max 自下而上;如需自上而下,在 slide 处理函数中交换 min/max 映射。

jquery-ui
$("#dialog").dialog({
  beforeClose: function (event, ui) {
    // Return false to prevent closing
    if (!confirm("Discard changes?")) return false;
  },
  open: function (event, ui) {
    console.log("Dialog opened");
  },
  close: function (event, ui) {
    console.log("Dialog closed");
    // Clean up form state
    $(this).find("form")[0].reset();
  },
  focus: function (event, ui) {
    // Dialog gained focus
  },
  dragStart: function (event, ui) { /* dragging started */ },
  dragStop: function (event, ui) { /* dragging ended */ },
  resizeStart: function (event, ui) { /* resizing started */ },
  resizeStop: function (event, ui) { /* resizing ended */ },
});

滑块方法

value()/values() 是手柄的 getter/setter(单柄用单数,范围用复数)。disable 置灰滑块并阻止输入。refresh 重新计算几何 —— 在容器调整大小或间接更改选项后调用。

jquery-ui
function confirmDialog(message, onConfirm) {
  $("<div>" + message + "</div>").dialog({
    modal: true,
    title: "Confirm",
    buttons: {
      "OK": function () {
        onConfirm();
        $(this).dialog("close");
      },
      "Cancel": function () {
        $(this).dialog("close");
      },
    },
    close: function () {
      $(this).dialog("destroy").remove();  // clean up
    },
  });
}

// Usage
confirmDialog("Delete this item?", function () {
  deleteItem();
});

滑块事件

slide 在拖动期间每次鼠标移动时触发(实时预览);start/stop 包围拖动。change 在值稳定时触发 —— 来自拖动停止、键盘箭头或编程 value()。对于'释放时提交'语义(如 AJAX 筛选),使用 change 或 stop,而非 slide。

jquery-ui
// Load content from a URL when opening
function openEditDialog(id) {
  var $dlg = $("#edit-dialog");
  $dlg.dialog({
    autoOpen: false,
    modal: true,
    open: function () {
      $dlg.load("/api/edit/" + id, function () {
        // Initialize widgets in loaded content
        $dlg.find(".datepicker").datepicker();
      });
    },
    close: function () {
      $dlg.empty();  // clear for next open
    },
  });
  $dlg.dialog("open");
}

// Common methods
$("#dialog").dialog("open");
$("#dialog").dialog("close");
$("#dialog").dialog("isOpen");   // returns boolean
$("#dialog").dialog("moveToTop"); // bring to front
$("#dialog").dialog("option", "title", "New Title");
13

工具提示

基础工具提示

在 document(或容器)上调用 tooltip() 会将其内所有原生 title 工具提示替换为带主题的工具提示 —— 适用于每个有 title 属性的元素。默认主题将其样式化为小黄色框;ThemeRoller 主题重新样式化以匹配。

jquery-ui
<div id="progress"></div>

<script>
  $(function () {
    $("#progress").progressbar({ value: 37 });
  });
</script>

自定义内容

content 作为函数返回每个元素的动态/HTML 内容(如提取 data-* 属性或执行 AJAX)。items 限制哪些元素触发工具提示(默认:[title])。返回 HTML 可嵌入图标、链接或格式化。

jquery-ui
<div id="progress"></div>

<script>
  // Set value to false for an indeterminate (animated) bar
  $("#progress").progressbar({ value: false });

  // Switch to determinate later when you know the percent
  $("#progress").progressbar("option", "value", 50);
</script>

跟踪鼠标与定位

track:true 使工具提示随鼠标移动。position 使用 Position 工具相对于元素(或 track 时的光标)放置工具提示。show/hide 配置打开/关闭动画。偏移如 'left+15' 添加间距,使工具提示不覆盖光标。

jquery-ui
$("#progress").progressbar({
  value: 0,           // 0-100, or false for indeterminate
  max: 100,           // upper bound (default 100)
  disabled: false,
  // 1.12+ supports a 'classes' option for theming
  classes: {
    "ui-progressbar": "highlight",
    "ui-progressbar-value": "animated",
  },
});

自定义元素与选择器

items 允许为使用自定义属性(data-*)而非 title 的元素添加工具提示 —— 当 title 会在别处显示原生工具提示或需要富内容时很有用。content 通过 .data() 或 .attr() 读取属性并返回。适用于 <area>、<img>、任何元素。

jquery-ui
// Simulate a file upload
var progress = 0;
$("#progress").progressbar({ value: 0 });

var timer = setInterval(function () {
  progress += 5;
  $("#progress").progressbar("option", "value", progress);
  if (progress >= 100) {
    clearInterval(timer);
    console.log("Complete!");
  }
}, 200);

// Get current value
var current = $("#progress").progressbar("option", "value");

工具提示方法

open/close 强制工具提示的可见性(如表单字段的聚焦)。disable 隐藏所有工具提示但不销毁组件。对于动态添加的元素,确保它们在调用 tooltip() 的容器内,或在新子树上再次调用 tooltip()。

jquery-ui
$("#progress").progressbar({
  value: 0,
  change: function () {
    var v = $("#progress").progressbar("value");
    $("#progress .ui-progressbar-value")
      .css("background", v < 50 ? "#fa0" : "#0a0");
  },
  complete: function () {
    $("#progress .ui-progressbar-value").css("background", "#0a0");
    $("#progress-label").text("Done!");
  },
});

// Overlay a text label
$("#progress").append(
  '<div id="progress-label" style="position:absolute;left:50%;top:0;">Loading...</div>'
);
14

拖拽

基础拖拽

draggable() 使任何元素可通过鼠标移动。默认元素跟随光标在页面任意位置移动。组件添加 ui-draggable 类并管理定位(根据需要使用 relative 或 absolute)。结合 droppable 创建放置目标。

jquery-ui
<label for="speed">Speed:</label>
<select id="speed">
  <option>Slower</option>
  <option>Slow</option>
  <option selected="selected">Medium</option>
  <option>Fast</option>
  <option>Faster</option>
</select>

<script>
  $(function () {
    $("#speed").selectmenu();
  });
</script>

轴与约束

axis:'x'/'y' 将拖动限制在一个轴。containment 将移动限制在父元素、元素/选择器或显式 [x1,y1,x2,y2] 框内。cursor 设置拖动光标;cursorAt 将光标锁定在辅助元素角落的固定偏移处,确保可预测的放置。

jquery-ui
$("#speed").selectmenu({
  disabled: false,
  width: null,            // null = CSS width, number = px
  icons: { button: "ui-icon-triangle-1-s" },
  appendTo: null,         // where to render the menu
  position: { my: "left top", at: "left bottom" },
});

手柄与取消

handle 将拖动启动限制在子元素(经典的'标题栏'模式)。cancel 防止从某些子元素(链接、按钮、输入框)启动拖动,使其保持可交互。两者结合可构建仅通过标题栏拖动的窗口/面板。

jquery-ui
$("#speed").selectmenu({
  change: function (event, ui) {
    // ui.item has the selected option's data
    console.log("Selected:", ui.item.value);
    console.log("Label:", ui.item.label);
  },
  focus: function (event, ui) {
    // Item highlighted in the dropdown
  },
  open: function (event, ui) {
    // Dropdown just opened
  },
  close: function (event, ui) {
    // Dropdown just closed
  },
  select: function (event, ui) {
    // Fires before change; return false to cancel
  },
});

吸附、网格与辅助元素

snap 使被拖元素跳到附近目标边缘(snapMode 控制哪一侧)。grid 将位置约束为 [x,y] 的倍数。helper:'clone' 拖动副本(原件不动);helper 函数返回自定义拖动元素。opacity 使源在拖动期间半透明。

jquery-ui
$("#projects").selectmenu({
  // Render each item in the dropdown
  format: function (item) {
    // (deprecated in 1.12 — use _renderItem instead)
  },
});

// 1.12+ custom rendering via widget extension
$.widget("custom.iconselectmenu", $.ui.selectmenu, {
  _renderItem: function (ul, item) {
    var li = $("<li>"), wrapper = $("<div>", { text: item.label });
    if (item.disabled) li.addClass("ui-state-disabled");
    $("<span>", { class: "ui-icon " + item.element.data("icon") })
      .appendTo(wrapper);
    return li.append(wrapper).appendTo(ul);
  },
});

$("#projects").iconselectmenu();

回弹

revert:true 总是回弹到起点;'invalid' 仅在未放到有效 droppable 上时;'valid' 仅在成功放置时。revertDuration 是动画时间。对于自定义逻辑,使用 stop 事件并自行重定位元素。

jquery-ui
// Open / close programmatically
$("#speed").selectmenu("open");
$("#speed").selectmenu("close");

// Get or set the value
var val = $("#speed").selectmenu("option", "value");  // not standard
$("#speed").val("fast").selectmenu("refresh");  // use .val() + refresh

// Refresh after modifying the underlying select
$("#speed").append("<option>New</option>");
$("#speed").selectmenu("refresh");

// Disable / enable
$("#speed").selectmenu("disable");
$("#speed").selectmenu("enable");

// Get the button or menu element
$("#speed").selectmenu("widget");    // the button wrapper
$("#speed").selectmenu("menuWidget"); // the menu ul

// Destroy
$("#speed").selectmenu("destroy");

拖拽事件

start/drag/stop 包围拖动生命周期。ui.position 相对于 offset parent;ui.offset 是页面绝对位置。ui.helper 是视觉上被拖动的元素(可能是克隆)。drag 频繁触发 —— 保持处理函数轻量或在 stop 中去重繁重工作。

jquery-ui
<select id="category">
  <optgroup label="Frontend">
    <option value="react">React</option>
    <option value="vue">Vue</option>
  </optgroup>
  <optgroup label="Backend">
    <option value="node">Node.js</option>
    <option value="django" disabled>Django (deprecated)</option>
  </optgroup>
</select>

<script>
  $("#category").selectmenu({
    width: 200,
    change: function (event, ui) {
      console.log("Picked:", ui.item.value);
    },
  });
</script>
15

放置

基础放置

droppable() 将元素标记为可拖动元素的放置目标。当可拖动元素在其上释放时触发 drop 回调。ui.draggable 是被放置的元素。可拖动和可放置组件自动通信 —— 将它们配对可构建拖放界面。

jquery-ui
<div id="slider"></div>

<script>
  $(function () {
    $("#slider").slider();
  });
</script>

接受选择器

accept 限制此可放置组件接受哪些可拖动元素 —— 可以是选择器或返回 true/false 的函数。activeClass 在被接受的可拖动元素于任意位置拖动期间应用到可放置组件上;hoverClass 在其悬停于此可放置组件上时应用。非常适合视觉提示。

jquery-ui
$("#slider").slider({
  min: 0,
  max: 100,
  step: 1,                  // increment size
  value: 50,                // single value
  values: [25, 75],         // two-handle range (omit 'value')
  orientation: "horizontal", // or "vertical"
  range: true,              // or "min", "max"
  disabled: false,
  animate: "fast",          // or ms, or false
});

容差

tolerance 定义多少重叠才算“在可放置组件上”:'fit'(完全包含)、'intersect'(50% 重叠,默认)、'pointer'(光标在内)、'touch'(任意重叠)。'pointer' 对紧凑 UI 最直观;'fit' 适用于严格的基于槽位的布局。

jquery-ui
$("#slider").slider({
  start: function (event, ui) {
    // User started dragging a handle
    console.log("Start:", ui.value || ui.values);
  },
  slide: function (event, ui) {
    // Fires continuously during drag
    // Return false to prevent the handle from moving
    $("#label").text(ui.value);
  },
  change: function (event, ui) {
    // Fires after the handle is released (and on programmatic change)
    saveValue(ui.value);
  },
  stop: function (event, ui) {
    // User released the handle
  },
});

悬停与激活类

activeClass/hoverClass 添加视觉状态 —— active 在相关拖动发生的整个过程中生效,hover 仅当悬停于此目标上时生效。常见的 drop 处理函数将可拖动元素附加到目标(重新设置父节点)并重置其 top/left 使其紧贴。这是经典的看板/卡片移动模式。

jquery-ui
<div id="range-slider"></div>
<p>Price: $<span id="min-price"></span> - $<span id="max-price"></span></p>

<script>
  $("#range-slider").slider({
    range: true,
    min: 0,
    max: 500,
    values: [75, 300],
    slide: function (event, ui) {
      $("#min-price").text(ui.values[0]);
      $("#max-price").text(ui.values[1]);
    },
  });
</script>

放置动作:移动/复制

对于移动,将原始可拖动元素附加到目标。对于复制,使用 helper:'clone' 拖动并在放置时克隆 helper(而非原件),去除拖动类后附加。克隆模式是工具调色板和设计画布界面的基础。

jquery-ui
// Vertical slider
$("#vertical").slider({
  orientation: "vertical",
  min: 0,
  max: 100,
  value: 60,
});

// Vertical range
$("#vertical-range").slider({
  orientation: "vertical",
  range: true,
  min: 0,
  max: 100,
  values: [20, 80],
});

/* CSS: vertical sliders need a height */
/* #vertical { height: 200px; } */
</script>

放置事件

activate/deactivate 包围整个拖动(任意位置)。over/out 在可拖动元素进入/离开此可放置组件时触发。drop 是主要事件 —— 仅在成功放置时触发。使用 over/out 实现悬停提示,drop 处理实际业务逻辑。

jquery-ui
// Get or set the value
$("#slider").slider("value");
$("#slider").slider("value", 75);

// Get or set both handles of a range slider
var vals = $("#slider").slider("values");  // [25, 75]
$("#slider").slider("values", 0, 30);      // set lower handle
$("#slider").slider("values", [30, 90]);   // set both

// Get or set options
$("#slider").slider("option", "max", 200);
$("#slider").slider("option", "disabled", true);

// Disable / enable / destroy
$("#slider").slider("disable");
$("#slider").slider("enable");
$("#slider").slider("destroy");
16

调整大小

基础调整大小

resizable() 为元素添加调整大小手柄(默认为拖动角落)。用户拖动手柄改变宽高。组件在用户拖动时设置显式的像素宽高,并发出 resize 事件。结合 alsoResize 可同步调整同级元素。

jquery-ui
<label for="qty">Quantity:</label>
<input id="qty" type="text" value="1">

<script>
  $(function () {
    $("#qty").spinner();
  });
</script>

纵横比与网格

aspectRatio:true 锁定当前比例;如 16/9 的数字锁定特定比例。grid 将调整大小吸附到 [x,y] 的倍数。minWidth/maxWidth/minHeight/maxHeight 限制调整范围。它们共同将调整约束到合理值。

jquery-ui
$("#qty").spinner({
  min: 0,                   // minimum value
  max: 100,                 // maximum value
  step: 1,                  // increment size
  page: 10,                 // page up/down increment
  numberFormat: "n",        // "n" for number, "C" for currency
  culture: "en-US",         // locale for formatting
  disabled: false,
  incremental: true,        // accelerate while holding
  icons: {
    up: "ui-icon-triangle-1-n",
    down: "ui-icon-triangle-1-s",
  },
});

手柄与幽灵

handles 选择哪些边/角获得拖动手柄('n'、'e'、's'、'w' 及组合),或通过对象映射到自定义元素。ghost:true 在拖动时显示半透明预览,仅在释放时提交尺寸(减少布局抖动)。animate 平滑过渡到新尺寸。

jquery-ui
<!-- Requires Globalize.js for culture support -->
<script src="globalize.js"></script>
<script src="globalize.culture.ja-JP.js"></script>

<script>
  // Currency spinner (Japanese yen)
  $("#price").spinner({
    numberFormat: "C",
    culture: "ja-JP",
    step: 100,
    min: 0,
  });

  // Decimal spinner
  $("#weight").spinner({
    step: 0.01,
    numberFormat: "n2",  // 2 decimal places
    min: 0,
  });
</script>

同步调整与约束

alsoResize 同步调整其他元素(适用于成对面板)。containment 将调整限制在父元素内,无法拖出布局。对于垂直分割条,在左面板使用 handles:'e' 并在 resize 回调中调整右面板 —— 经典的主/详情分割。

jquery-ui
$("#qty").spinner({
  spin: function (event, ui) {
    // Fires when a button is clicked or arrow pressed
    // ui.value is the new value
    // Return false to cancel the change
    if (ui.value > 10) {
      alert("Max 10 per order");
      return false;
    }
  },
  change: function (event, ui) {
    // Fires when the value changes and input loses focus
    // ui.value may be null if invalid
    if (ui.value === null) {
      alert("Please enter a valid number");
    }
  },
  start: function (event, ui) { /* spin started */ },
  stop: function (event, ui) { /* spin stopped */ },
});

方法与动画

option 在运行时获取/设置任意选项。disable 冻结调整(隐藏手柄)。destroy 移除组件。animate:true 时元素在释放时缓动到新尺寸 —— 适用于应滑动而非跳跃的吸附网格布局。

jquery-ui
// Time spinner (steps of 15 minutes)
$("#time").spinner({
  step: 15,
  min: 0,
  max: 1439,  // 24 * 60 - 1
  numberFormat: "n0",
  spin: function (event, ui) {
    // Wrap around at midnight
    if (ui.value > 1439) return false;  // or wrap: $(this).spinner("value", 0);
  },
});

// Methods
$("#qty").spinner("value");        // get current value
$("#qty").spinner("value", 5);     // set value
$("#qty").spinner("stepUp");       // increment by one step
$("#qty").spinner("stepDown");     // decrement by one step
$("#qty").spinner("pageUp");       // increment by 'page' steps
$("#qty").spinner("pageDown");
$("#qty").spinner("disable");
$("#qty").spinner("enable");
$("#qty").spinner("destroy");

调整大小事件

start/resize/stop 包围调整过程。ui.size 是当前 {width,height};ui.originalSize 是起始值。resize 持续触发 —— 在此更新实时尺寸指示器。stop 是持久化新尺寸的位置(cookie、服务器、布局存储)。

jquery-ui
// Custom spinner for hexadecimal colors
$.widget("custom.hexspinner", $.ui.spinner, {
  _parse: function (value) {
    // String -> number
    return parseInt(value, 16);
  },
  _format: function (value) {
    // number -> string
    return value.toString(16).toUpperCase().padStart(6, "0");
  },
});

$("#color").hexspinner({
  min: 0x000000,
  max: 0xffffff,
  step: 0x10,
});

// Prevent invalid input
$("#qty").on("keydown", function (e) {
  if (e.key === "-" && $(this).spinner("option", "min") >= 0) {
    e.preventDefault();
  }
});
17

可选择

基础可选择

selectable() 让用户通过点击、Ctrl 点击(添加)、Shift 点击(范围)或套索拖拽矩形来选择项。选中的项获得 ui-selected 类。组件适用于任何子元素的容器(ol、ul、div 嵌套 div)。

jquery-ui
<div id="tabs">
  <ul>
    <li><a href="#tab-1">First</a></li>
    <li><a href="#tab-2">Second</a></li>
    <li><a href="#tab-3">Third</a></li>
  </ul>
  <div id="tab-1">Content 1</div>
  <div id="tab-2">Content 2</div>
  <div id="tab-3">Content 3</div>
</div>

<script>
  $(function () {
    $("#tabs").tabs();
  });
</script>

过滤与套索

filter 限制哪些子元素可被选择(如 'li.item')。distance 防止点击时意外启动套索(必须先拖动 N 像素)。delay 在启动前等待 N 毫秒。cancel 排除某些子元素使其保持可点击。

jquery-ui
$("#tabs").tabs({
  active: 0,            // index of active tab (false = all hidden)
  collapsible: false,   // allow closing the active tab
  disabled: [],         // array of disabled indices
  event: "click",       // event to switch tabs ("mouseover" etc.)
  heightStyle: "content", // "auto", "fill", or "content"
  show: { effect: "fadeIn", duration: 200 },
  hide: { effect: "fadeOut", duration: 200 },
});

选中项与样式

拖动套索时,项获得 ui-selecting;释放时切换到 ui-selected(未选中则失去)。在 CSS 中为两个类设置样式。在 selectablestop 上查询 .ui-selected 读取最终选择 —— map().get() 将 jQuery 集合转为普通数组。

jquery-ui
$("#tabs").tabs({
  beforeActivate: function (event, ui) {
    // ui.newTab, ui.newPanel (opening)
    // ui.oldTab, ui.oldPanel (closing)
    // Return false to cancel the switch
    if ($(ui.newPanel).find("form").hasUnsavedChanges()) {
      return confirm("Discard changes?");
    }
  },
  activate: function (event, ui) {
    // Fires after the new tab is shown
    console.log("Now on:", ui.newTab.text());
  },
  beforeLoad: function (event, ui) {
    // For AJAX tabs — fires before loading remote content
    ui.jqXHR.error(function () {
      ui.panel.text("Failed to load content.");
    });
  },
  load: function (event, ui) {
    // AJAX content finished loading
  },
});

可选择事件

selecting/selected 在项进入/确认选择时触发;unselecting/unselected 在离开时触发(Ctrl 拖动取消选择)。ui.selecting/ui.selected 等指向受影响元素。start/stop 包围整个手势。这些为实时 UI 更新提供细粒度钩子。

jquery-ui
<div id="tabs">
  <ul>
    <li><a href="#local">Local</a></li>
    <li><a href="remote.html">Remote (AJAX)</a></li>
    <li><a href="api/data.json">API Data</a></li>
  </ul>
  <div id="local">This content is in the page.</div>
  <!-- Remote panels are created automatically -->
</div>

<script>
  $("#tabs").tabs({
    beforeLoad: function (event, ui) {
      // Show a loading indicator
      ui.panel.html("Loading...");
      // Cache the loaded content
      ui.ajaxSettings.cache = true;
    },
  });
</script>

可选择方法

disable/enable 切换组件。option 在运行时重新配置。对于编程式选择,只需自行添加/移除 ui-selected 类 —— 组件并不强制它。当不需要套索时,click+Ctrl 模式模仿原生多选列表。

jquery-ui
// Allow collapsing the active tab
$("#tabs").tabs({ collapsible: true });

// Make tabs reorderable by drag
$("#tabs").tabs().find(".ui-tabs-nav").sortable({
  axis: "x",
  stop: function () {
    $("#tabs").tabs("refresh");
  },
});

// Dynamically add a new tab
function addTab(id, label, content) {
  var nav = $("#tabs .ui-tabs-nav");
  nav.append('<li><a href="#' + id + '">' + label + '</a></li>');
  $("#tabs").append('<div id="' + id + '">' + content + '</div>');
  $("#tabs").tabs("refresh");
}

Tabs Methods

disable/enable accept an index or array of indices. The active option is both getter and setter for the current tab — use it to programmatically switch. load() reloads AJAX content for a tab. refresh() is essential after adding, removing, or reordering tabs.

jquery-ui
// Disable / enable specific tabs
$("#tabs").tabs("disable", 1);       // disable second tab
$("#tabs").tabs("enable", 1);
$("#tabs").tabs("option", "disabled", [0, 2]);  // disable multiple

// Switch to a tab by index
$("#tabs").tabs("option", "active", 2);

// Reload an AJAX tab
$("#tabs").tabs("load", 1);

// Refresh after structural changes
$("#tabs").tabs("refresh");

// Get the active tab index
var active = $("#tabs").tabs("option", "active");

// Destroy
$("#tabs").tabs("destroy");
18

排序

基础排序

sortable() 让用户通过拖放重新排列子元素。拖动时,组件在项将落下的位置插入占位符并相应移动同级元素。DOM 顺序在释放时更新 —— 通过 children() 或 toArray() 读回。

jquery-ui
<label for="age">Age:</label>
<input id="age" title="Please enter your age in years">

<script>
  $(function () {
    $(document).tooltip();
  });
</script>

占位符

placeholder 是应用到显示项将落下位置的空槽的 CSS 类 —— 样式设为虚线轮廓。forcePlaceholderSize 使其匹配项的尺寸(否则可能塌陷)。helper:'clone' 拖动半透明副本。axis 约束移动方向。

jquery-ui
$(document).tooltip({
  content: function () {
    // Default: returns the element's title attribute
    return $(this).attr("title");
  },
  items: "[title]",       // which elements get tooltips
  position: { my: "left top+15", at: "left bottom" },
  show: { effect: "fadeIn", duration: 200 },
  hide: { effect: "fadeOut", duration: 200 },
  tooltipClass: "custom-tooltip",  // class for the tooltip div
  track: false,           // follow the mouse cursor
  disabled: false,
  close: null,            // (event defaults handle this)
});

连接列表

connectWith 链接多个可排序列表,使项可在其间拖动(Trello 风格看板)。每个列表可接收和捐出项。在列表上 disableSelection() 防止文本选择干扰拖动。接收列表触发 receive/update 事件。

jquery-ui
<!-- HTML with data attributes -->
<a href="#" class="help" data-help="Click to save your changes">Save</a>
<a href="#" class="help" data-help="Undo the last action">Undo</a>

<script>
  $(".help").tooltip({
    content: function () {
      return "<strong>Help:</strong> " + $(this).data("help");
    },
    tooltipClass: "help-tooltip",
  });
</script>

<!-- With an image preview -->
$(".thumb").tooltip({
  content: function () {
    var src = $(this).attr("href");
    return "<img src='" + src + "' width='200'>";
  },
});

轴、手柄与项

handle 将拖动启动限制到特定子元素(如抓取图标),使文本/输入框保持可用。items 过滤哪些子元素可排序(如排除分隔符或锁定行)。tolerance:'pointer' 基于光标位置重排 —— 比默认 50% 重叠的 'intersect' 更灵敏。

jquery-ui
$(".help").tooltip({
  open: function (event, ui) {
    // Tooltip just appeared
    ui.tooltip;  // the tooltip element
  },
  close: function (event, ui) {
    // Tooltip just disappeared
    ui.tooltip.one("transitionend", function () {
      // Cleanup after the hide animation
    });
  },
  create: function (event, ui) {
    // Widget initialized
  },
});

// Prevent tooltip from closing on hover
$(".help").tooltip({
  close: function (event, ui) {
    ui.tooltip.hover(
      function () { $(this).stop(true).fadeIn(); },
      function () { $(this).fadeOut(); }
    );
  },
});

排序方法

toArray() 以新顺序返回 id(在每个项上设置 id)。serialize() 构建用于表单/AJAX 提交的查询字符串(使用如 'item_3' 的 id -> sort[]=3)。refresh 在添加/删除项后重新读取 DOM。cancel 撤销最近一次排序。这些支持“保存顺序”按钮。

jquery-ui
$("#target").tooltip({
  position: {
    my: "center top",       // tooltip's anchor point
    at: "center bottom",    // target's anchor point
    of: "#target",          // optional: position relative to this
    collision: "flip",      // "flip", "fit", "flipfit", "none"
    using: function (pos, feedback) {
      $(this).css(pos);
      console.log(feedback.horizontal, feedback.vertical);
    },
  },
});

// Methods
$("#target").tooltip("open");   // show programmatically
$("#target").tooltip("close");  // hide programmatically
$("#target").tooltip("disable");
$("#target").tooltip("enable");
$("#target").tooltip("widget");  // get the tooltip div
$("#target").tooltip("destroy");

排序事件

update 仅在顺序实际改变且拖动结束时触发 —— 在此持久化(AJAX/serialize)。change 在拖动期间的每次重排时触发(实时)。receive/remove 在连接列表场景下项在列表间移动时触发;ui.sender 是源列表。

jquery-ui
<!-- Show validation errors as tooltips -->
<form id="form">
  <input id="email" type="text" placeholder="Email">
  <input id="submit" type="submit" value="Submit">
</form>

<script>
  $("#form").tooltip({
    items: "input",
    content: function () {
      return $(this).data("error") || "";
    },
    position: { my: "left top", at: "left bottom+5" },
    tooltipClass: "error-tooltip",
    open: function (event, ui) {
      var el = $(event.originalEvent.target);
      if (!el.data("error")) return false;  // don't show if no error
    },
  });

  $("#submit").on("click", function (e) {
    var email = $("#email").val();
    if (!email.includes("@")) {
      e.preventDefault();
      $("#email").data("error", "Please enter a valid email")
                 .tooltip("open");
    }
  });
</script>
19

特效

show/hide/toggle 特效

jQuery UI 扩展了 jQuery 的 show/hide/toggle 以接受特效名加选项/时长/缓动。每个特效动画方式不同 —— blind(卷起)、explode(碎片飞出)、fold、slide 等。传入选项对象设置特效特定参数如 direction。

jquery-ui
// Built-in effects (beyond jQuery's show/hide/toggle)
$("#box").hide("fade", {}, 1000);    // fade out
$("#box").show("slide", {}, 500);    // slide in
$("#box").toggle("explode", {}, 800); // explode toggle
$("#box").effect("bounce", { times: 3 }, 300);

// Available effect names:
// blind, bounce, clip, drop, explode, fade, fold,
// highlight, puff, pulsate, scale, shake, size, slide, transfer

添加/移除/切换类

jQuery UI 的 addClass/removeClass/toggleClass 接受时长,在旧和新类状态之间平滑过渡元素的样式(颜色、尺寸、位置)。无时长时行为同 jQuery 核心(即时)。用于动画 CSS 中定义的状态转换。

jquery-ui
// jQuery core provides: swing (default), linear
// jQuery UI adds ~30 more easing functions
$("#box").animate({ width: 500 }, 1000, "easeInOutBounce");

// Available easings (subset):
// easeInQuad, easeOutQuad, easeInOutQuad
// easeInCubic, easeOutCubic, easeInOutCubic
// easeInQuart, easeOutQuart, easeInOutQuart
// easeInExpo, easeOutExpo, easeInOutExpo
// easeInBack, easeOutBack, easeInOutBack
// easeInBounce, easeOutBounce, easeInOutBounce
// easeInElastic, easeOutElastic, easeInOutElastic

切换类

switchClass 在两个类之间动画转换 —— 适用于交换主题、布局或尺寸差异超过一个属性的情况。比 removeClass + addClass 更干净,因为样式直接插值。结合缓动增加打磨感。

jquery-ui
// show with an effect
$("#box").show("drop", { direction: "left" }, 500);

// hide with an effect
$("#box").hide("puff", {}, 500);

// toggle with an effect
$("#box").toggle("scale", { percent: 0 }, 500);

// With a callback
$("#box").hide("blind", 500, function () {
  console.log("Animation complete");
});

// Direction option (where applicable)
$("#box").hide("slide", { direction: "up" });

动画与颜色动画

jQuery UI 扩展 .animate() 以动画颜色属性(背景、边框、颜色、轮廓),这是 jQuery 核心做不到的。对状态闪烁、悬停转换和主题切换非常有用。可在单个 animate 调用中混合颜色和数值属性。

jquery-ui
// jQuery UI extends animate() to support colors
$("#box").animate({
  backgroundColor: "#ff0000",
  color: "#ffffff",
  borderColor: "#000000",
}, 1000);

// Animate through the theme states
$("#box").animate(
  { backgroundColor: $.Color("#0a0") },
  { duration: 500 }
);

// Toggle class with smooth transitions
$("#box").switchClass("old-class", "new-class", 500);
$("#box").toggleClass("active", 500);  // duration = animated

缓动

jQuery UI 提供 Robert Penner 的缓动方程 —— easeOutBounce 用于活泼弹簧,easeInOutBack 用于轻微过冲,easeInOutCubic 用于平滑运动。在选项对象中以字符串传入或作为 animate 的第三个参数。选择匹配运动意图的缓动。

jquery-ui
// Add/remove classes with animation
$("#box").addClass("highlight", 500);    // animate to new class
$("#box").removeClass("highlight", 500);
$("#box").toggleClass("highlight", 500);

// switchClass: smoothly transition from one class to another
$("#box").switchClass("state-default", "state-active", 500);

// All accept a callback
$("#box").addClass("expanded", 500, function () {
  console.log("Done expanding");
});

缩放、转移与裁剪

scale 将元素尺寸动画到百分比。transfer 动画一个从某元素飞到另一元素的占位轮廓(经典的“加入购物车”反馈)。clip 通过遮罩显示/隐藏。.effect() 运行特效(shake、highlight、pulsate、bounce)而不改变可见性 —— 非常适合引起注意。

jquery-ui
// .effect() — run an effect without hiding
$("#box").effect("shake", { times: 3 }, 300);

// .transfer() — animate a transfer outline to another element
$("#product").effect("transfer", { to: "#cart" }, 500);

// .animate() with colors and easing
$("#box").animate({ left: 200, opacity: 0.5 }, "slow", "easeOutBounce");

// Custom animation with step
$("#box").animate({
  width: ["toggle", "swing"],   // [value, easing] per property
  height: ["toggle", "linear"],
}, 1000);
20

ThemeRoller 与主题定制

ThemeRoller 工作流

ThemeRoller 是构建自定义 jQuery UI 主题的可视化工具 —— 调整框架和各组件设置,然后下载 CSS 文件。快速需求可从 CDN 使用约 24 个预构建主题(smoothness、redmond、ui-darkness...)。替换主题 CSS 文件即可即时重设所有组件样式。

jquery-ui
<!-- Use a prebuilt theme from the CDN -->
<link rel="stylesheet"
      href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">

<!-- Or a custom theme from ThemeRoller (jqueryui.com/themeroller) -->
<!-- 1. Visit the ThemeRoller app -->
<!-- 2. Customize colors, fonts, corner radius, etc. -->
<!-- 3. Download the generated CSS file -->
<link rel="stylesheet" href="my-custom-theme/jquery-ui.css">

CSS 框架类

CSS 框架暴露任何组件(或你的标记)可用的可复用类:ui-widget(-header/-content)用于容器,ui-state-* 用于交互状态,ui-corner-* 用于主题圆角,ui-helper-* 用于如 clearfix 等工具。使用这些保持自定义 UI 与组件一致。

jquery-ui
<!-- The jQuery UI CSS framework is reusable for custom markup -->
<div class="ui-widget">
  <div class="ui-widget-header ui-corner-top">
    <h3>Panel Header</h3>
  </div>
  <div class="ui-widget-content ui-corner-bottom">
    <p>Panel content with themed styling.</p>
    <button class="ui-button ui-widget ui-state-default ui-corner-all">
      <span class="ui-icon ui-icon-gear"></span> Action
    </button>
  </div>
</div>

图标类

图标是精灵图 span:ui-icon 加 ui-icon-<名称>。主题定义精灵图,因此图标随主题重新着色。约 170 个图标(gear、disk、trash、calendar 等)。默认显示为 inline-block 但文本对齐各异 —— 包裹在按钮中或设置显式尺寸。ui-icon-white 强制浅色图标。

jquery-ui
/* ThemeRoller generates CSS with these key classes */
.ui-widget {
  font-family: Arial, sans-serif;   /* font family */
  font-size: 1em;                    /* base font size */
}
.ui-widget-content { border: 1px solid #aaa; background: #fff; color: #222; }
.ui-widget-header  { border: 1px solid #aaa; background: #ccc; color: #222; }
.ui-state-default  { border: 1px solid #d3d3d3; background: #e6e6e6; }
.ui-state-hover    { border: 1px solid #999;    background: #dadada; }
.ui-state-active   { border: 1px solid #aaa;    background: #fff; }
.ui-state-focus    { border: 1px solid #999;    background: #dadada; }
.ui-state-highlight { border: 1px solid #fcefa1; background: #fbf9ee; }
.ui-state-error     { border: 1px solid #cd0a0a; background: #fef1ec; }
.ui-corner-all { border-radius: 4px; }  /* themable radius */

自定义主题覆盖

通过在包装类(如 .my-app)下限定范围来覆盖主题样式 —— 这提升特异性而无需 !important。通过生成的类(.ui-datepicker、.ui-dialog)定位特定组件。将覆盖保存在主题 CSS 之后加载的单独文件中以赢得层叠。

jquery-ui
/* Load the base theme first */
@import url("https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css");

/* Override specific elements */
.ui-widget-header {
  background: linear-gradient(to bottom, #2c3e50, #34495e);
  color: #ecf0f1;
}
.ui-state-default {
  background: #3498db;
  border-color: #2980b9;
  color: #fff;
}
.ui-state-hover { background: #2980b9; }
.ui-state-active { background: #1abc9c; border-color: #16a085; }
.ui-corner-all { border-radius: 0; }  /* sharper look */

Z-Index 与堆叠

浮动组件(对话框、日期选择器、自动完成、工具提示)需要高 z-index。ui-front 是基础。常见 bug:对话框内的日期选择器出现在其后 —— 在 beforeShow 中提升 z-index。dialog 的 zIndex 选项控制其堆叠。通过复用框架的标尺避免手动 z-index 争斗。

jquery-ui
<!-- Two theme stylesheets; toggle the disabled attribute -->
<link id="theme-light" rel="stylesheet"
      href="themes/ui-lightness/jquery-ui.css">
<link id="theme-dark" rel="stylesheet"
      href="themes/ui-darkness/jquery-ui.css" disabled>

<script>
  function switchTheme(name) {
    $("#theme-light").prop("disabled", name !== "light");
    $("#theme-dark").prop("disabled", name !== "dark");
    localStorage.setItem("theme", name);
  }

  // Restore on load
  $(function () {
    var saved = localStorage.getItem("theme") || "light";
    switchTheme(saved);
  });
</script>

RTL 与无障碍

jQuery UI 尊重父元素上的 dir='rtl' —— 为从右到左语言(阿拉伯语、希伯来语)翻转布局、图标和滑块方向。每个组件注入正确的 ARIA 角色/属性(role='tablist'、aria-selected、aria-valuenow)和实时区域,加上键盘支持(箭头键、Esc、Tab)。使组件开箱即用支持屏幕阅读器。

jquery-ui
/* Datepicker: style the calendar popup */
.ui-datepicker {
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  border-radius: 0;
}
.ui-datepicker .ui-state-highlight { /* today */ background: #ffd; }
.ui-datepicker .ui-state-active {    /* selected */ background: #2c3e50; }

/* Dialog: remove the default rounded corners */
.ui-dialog { border-radius: 0; box-shadow: 0 8px 30px rgba(0,0,0,0.3); }

/* Accordion: modernize the headers */
.ui-accordion .ui-accordion-header {
  background: #f5f5f5;
  border: none;
  border-bottom: 1px solid #ddd;
  font-weight: bold;
}

/* Use the 'classes' option (1.12+) for per-widget theming */
$("#dialog").dialog({
  classes: { "ui-dialog": "my-dialog", "ui-dialog-titlebar": "my-title" },
});

这篇内容对您有帮助吗?

学习路径

从零开始学习

通过结构化课程从头学习这个语言。