Skip to content

jQuery Mobile 速查表

用于移动 Web 应用的触摸优化 HTML5 UI 框架。

01

入门

页面结构

jQuery Mobile 使用 data-role 属性增强 HTML。一个页面是带有 data-role=page 的 div,包含 header、main 和 footer 部分。viewport meta 标签对于在移动设备上正确缩放至关重要。需在 jquery.mobile.js 之前加载 jQuery 核心。

jquery-mobile
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
  <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
  <div data-role="page" id="home">
    <div data-role="header"><h1>Home</h1></div>
    <div data-role="main" class="ui-content">Content</div>
    <div data-role="footer"><h4>Footer</h4></div>
  </div>
</body>
</html>

单文档多页面

可以在单个 HTML 文件中放置多个 data-role=page 的 div。通过锚点 href(#about)在它们之间链接。jQuery Mobile 一次只显示一个页面并执行过渡动画。初始加载时只显示源代码顺序中的第一个页面。

jquery-mobile
<div data-role="page" id="home">
  <div data-role="header"><h1>Home</h1></div>
  <div data-role="main" class="ui-content">
    <a href="#about" class="ui-btn">Go to About</a>
  </div>
</div>

<div data-role="page" id="about" data-theme="b">
  <div data-role="header"><h1>About</h1></div>
  <div data-role="main" class="ui-content">
    <a href="#home" class="ui-btn" data-direction="reverse">Back</a>
  </div>
</div>

AJAX 导航与链接

默认情况下,指向内部(#id)和同源页面的链接会通过 AJAX 获取并以过渡动画切换。使用 data-ajax=false 可强制进行正常的整页加载(适用于非 jQuery Mobile 页面)。data-prefetch 会预加载目标页面,使过渡瞬时完成。

jquery-mobile
<!-- Default: links load via AJAX and animate a transition -->
<a href="detail.html" class="ui-btn">Open detail (AJAX)</a>

<!-- Force a full page reload (no AJAX) -->
<a href="external.html" data-ajax="false">Full reload</a>

<!-- Open in new window/tab -->
<a href="https://example.com" rel="external">External site</a>

<!-- Prefetch a page when this page loads -->
<a href="next.html" data-prefetch="true" class="ui-btn">Prefetch next</a>

预取与 DOM 缓存

预取在后台加载链接的页面,使导航感觉是即时的。默认情况下已访问的页面会从 DOM 中移除,但 domCache 会保留它们以加快后退导航,代价是占用更多内存。可通过 data-dom-cache 单页启用,或通过 page prototype 选项全局启用。

jquery-mobile
<!-- Prefetch several pages -->
<a href="page1.html" data-prefetch="true">Page 1</a>
<a href="page2.html" data-prefetch="true">Page 2</a>

<!-- Globally enable DOM caching of visited pages -->
<script>
$(document).on("mobileinit", function () {
  $.mobile.page.prototype.options.domCache = true;
});
</script>

<!-- Cache a single page -->
<div data-role="page" id="cached" data-dom-cache="true">...</div>

对话框页面

为链接添加 data-rel=dialog(或在页面上设置 data-dialog=true)可打开一个样式为模态对话框的页面,带有关闭按钮和过渡动画。在链接上使用 data-rel=back 可关闭它并返回上一页。

jquery-mobile
<!-- Open a page as a dialog -->
<a href="#dialog" class="ui-btn" data-rel="dialog">Open dialog</a>

<div data-role="page" id="dialog" data-dialog="true">
  <div data-role="header"><h1>Dialog</h1></div>
  <div data-role="main" class="ui-content">
    <p>This page is styled as a dialog.</p>
    <a href="#" class="ui-btn" data-rel="back">Close</a>
  </div>
</div>

全局配置 (mobileinit)

mobileinit 事件在 jQuery 核心加载之后、jQuery Mobile 初始化之前触发——在此处(引入 jquery.mobile.js 之前)绑定你的配置。常见的覆盖项:默认过渡、AJAX 设置和加载提示文字。设置 autoInitializePage=false 可让你控制首屏页面何时初始化。

jquery-mobile
<script src="jquery-1.11.1.min.js"></script>
<script>
// Bind BEFORE loading jquery.mobile.js
$(document).on("mobileinit", function () {
  $.mobile.defaultPageTransition = "slide";
  $.mobile.defaultDialogTransition = "pop";
  $.mobile.loadingMessage = "Loading...";
  $.mobile.ajaxEnabled = true;
  $.mobile.linkBindingEnabled = true;
  $.mobile.autoInitializePage = true;
});
</script>
<script src="jquery.mobile-1.4.5.min.js"></script>
02

页面过渡

基础过渡

为链接添加 data-transition 可选择导航时的动画。过渡基于 CSS(在可能时硬件加速)。'none' 跳过动画以实现即时导航。该属性同样适用于对话框和弹出框。

jquery-mobile
<!-- Apply a transition to a link -->
<a href="#page2" data-transition="slide">Slide</a>
<a href="#page2" data-transition="fade">Fade</a>
<a href="#page2" data-transition="pop">Pop</a>
<a href="#page2" data-transition="flip">Flip</a>
<a href="#page2" data-transition="none">None (instant)</a>

过渡类型

jQuery Mobile 内置一组 2D/3D CSS 过渡。3D 过渡(turn、flow、flip)在支持的设备上效果出色,但在旧硬件上会优雅降级。pop 和 fade 性能最佳,推荐用于对话框和弹出框。

jquery-mobile
<!-- Available transitions in jQuery Mobile 1.4 -->
fade      <!-- default, fade in/out -->
pop       <!-- scale in from center (good for dialogs) -->
slide     <!-- slide left to right -->
slideup   <!-- slide up from bottom -->
slidedown <!-- slide down from top -->
slidfade  <!-- slide + fade -->
turn      <!-- 3D turn -->
flow      <!-- 3D flow -->
flip      <!-- 3D flip -->
none      <!-- no animation -->

方向与反向

data-direction=reverse 反向播放过渡——通常用于“返回”按钮,使动画与前进导航镜像对应。它与 data-transition 配合使用;若未设置过渡,则反向播放默认过渡。

jquery-mobile
<!-- Reverse a transition (e.g., for Back buttons) -->
<a href="#home" data-transition="slide" data-direction="reverse">Back</a>

<!-- Globally reverse the default -->
<a href="#home" data-direction="reverse">Back (uses default transition reversed)</a>

对话框过渡

对话框可使用任何过渡,但 pop 和 slidedown 对模态框最为自然。在 mobileinit 期间用 $.mobile.defaultDialogTransition 设置全局默认值。对话框的关闭操作会自动反向播放过渡。

jquery-mobile
<!-- Combine data-rel=dialog with a transition -->
<a href="#settings" data-rel="dialog" data-transition="pop">Settings</a>
<a href="#settings" data-rel="dialog" data-transition="slidedown">Settings (slide down)</a>

<!-- Set a global default dialog transition -->
<script>
$(document).on("mobileinit", function () {
  $.mobile.defaultDialogTransition = "pop";
});
</script>

禁用与降级

设置 data-transition=none 或将全局默认值设为 'none' 可禁用动画——对低端设备或无障碍场景很有帮助。jQuery Mobile 会自动检测 3D 变换支持,在不支持时将 3D 过渡(flip、turn、flow)降级为简单的淡入淡出。

jquery-mobile
<!-- Disable transitions for a specific link -->
<a href="#page2" data-transition="none">No animation</a>

<!-- Globally disable (useful for older devices / testing) -->
<script>
$(document).on("mobileinit", function () {
  $.mobile.defaultPageTransition = "none";
  $.mobile.defaultDialogTransition = "none";
});
</script>

<!-- 3D transitions fall back to fade when not supported -->
03

工具栏(页眉与页脚)

固定页眉与页脚

添加 data-position=fixed 可在页面滚动时将页眉或页脚固定在视口顶部/底部。默认情况下点击页面会切换工具栏的可见性。页面内容会获得内边距,以免被工具栏遮挡。

jquery-mobile
<div data-role="page" id="home">
  <div data-role="header" data-position="fixed">
    <h1>Fixed Header</h1>
  </div>
  <div data-role="main" class="ui-content">
    <p>Scroll the page — the toolbars stay in place.</p>
  </div>
  <div data-role="footer" data-position="fixed">
    <h4>Fixed Footer</h4>
  </div>
</div>

全屏工具栏

data-fullscreen=true 将固定工具栏覆盖在内容之上(半透明),而非预留空间。非常适合照片查看器或地图等希望内容填满屏幕的场景。工具栏与固定工具栏一样,在点击时出现/消失。

jquery-mobile
<div data-role="page" id="photo">
  <div data-role="header" data-position="fixed" data-fullscreen="true">
    <h1>Photos</h1>
  </div>
  <div data-role="main" class="ui-content">
    <img src="photo.jpg" style="width:100%">
  </div>
  <div data-role="footer" data-position="fixed" data-fullscreen="true">
    <h4>Footer over content</h4>
  </div>
</div>

持久工具栏

当两个页面的页脚(或页眉)具有相同的 data-id 和 data-position=fixed 时,工具栏会在页面过渡期间保持不变,而非随页面动画。这是持久底部导航栏的标准模式——每页只有激活链接会变化。

jquery-mobile
<!-- Both pages use the SAME data-id so the footer persists -->
<div data-role="page" id="home">
  <div data-role="footer" data-id="main-nav" data-position="fixed">
    <div data-role="navbar">
      <ul><li><a href="#home" class="ui-btn-active">Home</a></li>
      <li><a href="#settings">Settings</a></li></ul>
    </div>
  </div>
</div>

<div data-role="page" id="settings">
  <div data-role="footer" data-id="main-nav" data-position="fixed">
    <div data-role="navbar">
      <ul><li><a href="#home">Home</a></li>
      <li><a href="#settings" class="ui-btn-active">Settings</a></li></ul>
    </div>
  </div>
</div>

点击切换行为

用户点击页面时,固定工具栏会切换可见性。设置 data-tap-toggle=false 可让工具栏始终可见。相关的逐元素选项:data-hide-during-focus(输入框获得焦点时隐藏)和 data-update-page-padding(调整大小时重新应用页面内边距)。

jquery-mobile
<!-- Disable tap-to-toggle on a fixed toolbar -->
<div data-role="header" data-position="fixed" data-tap-toggle="false">
  <h1>Always visible</h1>
</div>

<!-- Globally turn off tap toggle -->
<script>
$(document).on("mobileinit", function () {
  $.mobile.toolbar.prototype.options.tapToggle = false;
});
</script>

工具栏主题与按钮

页眉可包含用 ui-btn-left / ui-btn-right 类定位的按钮。data-theme 设置工具栏的色板。data-iconpos=notext 仅显示图标以获得紧凑外观。页眉内的按钮会自动样式化为内联按钮。

jquery-mobile
<div data-role="header" data-theme="b">
  <a href="#" class="ui-btn-left" data-icon="home" data-iconpos="notext">Home</a>
  <h1>Title</h1>
  <a href="#" class="ui-btn-right" data-icon="gear" data-iconpos="notext">Settings</a>
</div>

动态更新工具栏

运行时更改工具栏标记后,调用 $(el).toolbar('refresh') 重新应用样式和内边距。toolbar 组件(1.4 引入)管理固定定位和点击切换;如果在页面创建后添加工具栏,需用 $().toolbar() 手动初始化。

jquery-mobile
<script>
// Update the header title and re-enhance after DOM change
$(function () {
  $("#my-header h1").text("New Title");
  $("#my-header").toolbar("refresh");
});
</script>

<div data-role="header" id="my-header" data-position="fixed">
  <h1>Old Title</h1>
</div>
05

按钮

按钮基础

任何带有 class=ui-btn(或 data-role=button)的 <a>,以及 <button> 和 <input type=button|submit|reset>,都会被自动增强为带样式的按钮。ui-btn 类是现代的将链接标记为按钮的方式,无需依赖 data-role。

jquery-mobile
<!-- Anchor button -->
<a href="#" class="ui-btn">Link Button</a>

<!-- <button> and <input> auto-enhanced -->
<button class="ui-btn">Button Element</button>
<input type="button" value="Input Button">
<input type="submit" value="Submit">

<!-- Use data-role explicitly -->
<a href="#" data-role="button">Anchor via role</a>

内联按钮

默认情况下按钮为全宽(块级)。添加 ui-btn-inline(或 data-inline=true)可使按钮仅与标签一样宽,从而让多个按钮并排。这对于“取消 | 确定”等操作行很有用。

jquery-mobile
<!-- Inline: only as wide as the content -->
<a href="#" class="ui-btn ui-btn-inline">A</a>
<a href="#" class="ui-btn ui-btn-inline">B</a>
<a href="#" class="ui-btn ui-btn-inline">C</a>

<!-- Default (block) buttons fill the width -->
<a href="#" class="ui-btn">Full-width button</a>

按钮图标

使用 ui-icon-{name} 添加图标,用 ui-btn-icon-{pos} 定位(left、right、top、bottom、notext)。ui-btn-icon-notext 隐藏文本仅显示图标——但为无障碍/屏幕阅读器仍需提供文本。

jquery-mobile
<a href="#" class="ui-btn ui-icon-home ui-btn-icon-left">Home</a>
<a href="#" class="ui-btn ui-icon-search ui-btn-icon-right">Search</a>
<a href="#" class="ui-btn ui-icon-gear ui-btn-icon-top">Settings</a>
<a href="#" class="ui-btn ui-icon-star ui-btn-icon-notext">Star (icon only)</a>
<a href="#" class="ui-btn ui-icon-delete ui-btn-icon-bottom">Delete</a>

图标位置与内联

data-iconpos 属性是 ui-btn-icon-* 类的旧版等价物。'notext' 仅显示图标(始终通过元素文本为屏幕阅读器保留可见文本)。可在同一个按钮上自由组合 inline 和 icon 类。

jquery-mobile
<!-- data-* equivalents -->
<a href="#" data-role="button" data-icon="home" data-iconpos="left">Home</a>
<a href="#" data-role="button" data-icon="home" data-iconpos="notext">Home</a>

<!-- Combine inline + icon -->
<a href="#" class="ui-btn ui-btn-inline ui-icon-plus ui-btn-icon-left">Add</a>
<a href="#" class="ui-btn ui-btn-inline ui-icon-minus ui-btn-icon-left">Remove</a>

迷你与禁用按钮

添加 ui-mini(或 data-mini=true)可获得更小、更紧凑的按钮——适用于密集的工具栏。用 ui-state-disabled(或在 <button>/<input> 上使用原生 disabled 属性)禁用按钮。禁用的按钮会忽略点击。

jquery-mobile
<!-- Mini (smaller) button -->
<a href="#" class="ui-btn ui-mini">Mini</a>

<!-- Disabled button -->
<a href="#" class="ui-btn ui-state-disabled">Disabled</a>

<!-- Native disabled -->
<button disabled>Disabled button</button>
<input type="submit" value="Go" disabled>

按钮组 (Controlgroup)

controlgroup 在视觉上将按钮聚为一组——相邻按钮共享圆角且无间隙。data-type=horizontal 将它们排成一行(适合分段控件);默认的 vertical 则垂直堆叠。它也可将复选框/单选框分组成一个统一的集合。

jquery-mobile
<div data-role="controlgroup" data-type="horizontal">
  <a href="#" class="ui-btn">Yes</a>
  <a href="#" class="ui-btn">No</a>
  <a href="#" class="ui-btn">Maybe</a>
</div>

<!-- Vertical group (default) -->
<div data-role="controlgroup">
  <a href="#" class="ui-btn">Option 1</a>
  <a href="#" class="ui-btn">Option 2</a>
</div>
06

列表视图

基础列表视图

为 <ul> 添加 data-role=listview 可将其变为触控友好的列表,具有全宽可点击的行。每个包含 <a> 的 <li> 会成为带右箭头的链接行。data-inset=true 将列表内嵌为带圆角和外边距,而非边缘到边缘。

jquery-mobile
<ul data-role="listview" data-inset="true">
  <li><a href="#">Apple</a></li>
  <li><a href="#">Banana</a></li>
  <li><a href="#">Cherry</a></li>
</ul>

内嵌列表

边缘到边缘列表跨越全宽(适合全屏菜单);内嵌列表有圆角和周围外边距(适合页面内的内容分区)。使用 data-inset=true 可获得内嵌列表,外观更像分组的设置面板。

jquery-mobile
<!-- Edge-to-edge (default) -->
<ul data-role="listview">
  <li><a href="#">Item 1</a></li>
</ul>

<!-- Inset: rounded, with margins -->
<ul data-role="listview" data-inset="true">
  <li><a href="#">Item 1</a></li>
  <li><a href="#">Item 2</a></li>
</ul>

列表分隔符

带有 data-role=list-divider 的 <li> 会成为不可点击的分区标题。data-autodividers=true 会根据每个项目文本的首字母自动插入分隔符——非常适合字母顺序的联系人列表。

jquery-mobile
<ul data-role="listview" data-inset="true">
  <li data-role="list-divider">Fruits</li>
  <li><a href="#">Apple</a></li>
  <li><a href="#">Banana</a></li>
  <li data-role="list-divider">Vegetables</li>
  <li><a href="#">Carrot</a></li>
</ul>

<!-- Auto dividers from first letter -->
<ul data-role="listview" data-autodividers="true">
  <li><a href="#">Alice</a></li>
  <li><a href="#">Bob</a></li>
</ul>

计数气泡与缩略图

在 <li> 内添加 class=ui-li-count 的 span 可在右侧显示数字计数气泡。使用 class=ui-li-thumb 的 <img>(通常 80x80)作为左侧缩略图。结合 <h3>/<p> 可创建丰富的、应用式的列表行。

jquery-mobile
<ul data-role="listview" data-inset="true">
  <!-- Count bubble -->
  <li><a href="#">Inbox <span class="ui-li-count">12</span></a></li>
  <!-- Thumbnail on the left -->
  <li>
    <a href="#">
      <img src="thumb.jpg" class="ui-li-thumb">
      <h3>Title</h3>
      <p>Description</p>
      <span class="ui-li-count">3</span>
    </a>
  </li>
</ul>

搜索过滤

data-filter=true 在列表上方添加一个搜索输入框,按文本实时过滤项目。data-filter-placeholder 自定义提示文字。data-filter-reveal=true 会隐藏所有项目,直到用户输入——适用于自动补全式查询。

jquery-mobile
<ul data-role="listview" data-filter="true"
    data-filter-placeholder="Search fruits...">
  <li><a href="#">Apple</a></li>
  <li><a href="#">Banana</a></li>
  <li><a href="#">Cherry</a></li>
</ul>

<!-- Filter reveals hidden items (collapsible search) -->
<ul data-role="listview" data-filter="true" data-filter-reveal="true">
  <li><a href="#">Hidden until searched</a></li>
</ul>

分裂按钮与嵌套列表

当 <li> 包含两个 <a> 元素时,jQuery Mobile 会渲染分裂按钮:主行导航到第一个链接,右侧单独的图标按钮(通过 data-split-icon 设置)打开第二个链接。<li> 内嵌套的 <ul> 会自动成为钻取式子页面。

jquery-mobile
<!-- Split button: row link + icon link on the right -->
<ul data-role="listview" data-split-icon="gear" data-inset="true">
  <li>
    <a href="#detail">Go to detail</a>
    <a href="#edit">Edit</a>
  </li>
</ul>

<!-- Nested list (child <ul> becomes a sub-page) -->
<ul data-role="listview">
  <li>Fruits
    <ul>
      <li><a href="#">Apple</a></li>
      <li><a href="#">Banana</a></li>
    </ul>
  </li>
</ul>
07

表单控件

表单结构与 AJAX 提交

jQuery Mobile 默认自动增强表单输入,并通过 AJAX 提交表单,显示加载旋转图标并过渡到结果页面。设置 data-ajax=false 可进行传统的整页提交(对于不使用现代 API 的文件上传是必需的)。

jquery-mobile
<form action="/submit" method="post" data-ajax="true">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name" placeholder="Your name">

  <button type="submit" class="ui-btn">Submit</button>
</form>

<!-- Disable AJAX for this form (normal full submit) -->
<form action="/upload" method="post" data-ajax="false">...</form>

文本输入与清除按钮

所有 HTML5 输入类型(text、email、tel、number、password、date 等)都具有一致样式。data-clear-btn=true 添加一个输入框内的清除(x)按钮。使用 data-role=none 可保留控件为纯原生输入,不应用 jQuery Mobile 样式。

jquery-mobile
<label for="email">Email</label>
<input type="email" id="email" data-clear-btn="true" placeholder="[email protected]">

<label for="phone">Phone</label>
<input type="tel" id="phone" data-clear-btn="true" data-clear-btn-text="Clear">

<!-- Non-enhanced native input -->
<input type="text" data-role="none">

字段容器

将 label + 控件对包裹在 class=ui-field-contain 的 div 中。在宽屏上标签和输入并排;在窄屏手机上它们垂直堆叠。此响应式行为取代了旧的 data-role=fieldcontain 属性。

jquery-mobile
<div class="ui-field-contain">
  <label for="user">Username</label>
  <input type="text" id="user">
</div>

<div class="ui-field-contain">
  <label for="pwd">Password</label>
  <input type="password" id="pwd">
</div>

搜索输入框

<input type=search> 会被增强为带放大镜图标的搜索字段。通过给输入框设置 id 并在 listview 的 filter 上设置 data-input=#id 来与列表视图配对——这让你可将搜索框放在页面任意位置。

jquery-mobile
<label for="q">Search</label>
<input type="search" id="q" placeholder="Search...">

<!-- Search input feeding a listview filter -->
<input type="search" id="my-filter" data-type="search">
<ul data-role="listview" data-filter="true"
    data-input="#my-filter">
  <li><a href="#">Apple</a></li>
  <li><a href="#">Banana</a></li>
</ul>

文本域与隐藏输入

文本域样式与其他输入一致,默认在输入时自动增高;设置 data-autogrow=false 可固定高度并使用滚动条。隐藏输入保持不变。与所有输入一样,将它们包裹在 ui-field-contain 中以获得响应式标签。

jquery-mobile
<label for="bio">Bio</label>
<textarea id="bio" placeholder="Tell us about you"></textarea>

<!-- Auto-grow textarea -->
<textarea id="bio" data-autogrow="false"></textarea>

<!-- Hidden inputs are not styled -->
<input type="hidden" name="id" value="42">

禁用自动增强

为任何控件添加 data-role=none 可跳过 jQuery Mobile 增强并保持原生。对于项目级规则,在 mobileinit 期间将 keepNative 设置为不应被增强的元素选择器字符串——在将自定义样式控件与 jQM 页面混用时很有用。

jquery-mobile
<!-- Keep a control native (no jQM styling) -->
<select data-role="none">...</select>
<input type="checkbox" data-role="none">

<!-- Globally disable enhancement for a tag -->
<script>
$(document).on("mobileinit", function () {
  $.mobile.page.prototype.options.keepNative = "select, input[type=checkbox]";
});
</script>
08

滑块

基础范围滑块

带有 min、max、value 和 step 的 <input type=range> 会被增强为带数值气泡的触控友好滑块。value 属性设置初始位置。滑块将其值写回输入框,因此会随表单正常提交。

jquery-mobile
<label for="volume">Volume</label>
<input type="range" name="volume" id="volume"
       value="50" min="0" max="100" step="1">

带高亮的滑块

data-highlight=true 用活动主题色填充滑块左侧的轨道,清晰显示当前级别。不设置时轨道为单一平色。适用于音量或亮度等设置。

jquery-mobile
<label for="brightness">Brightness</label>
<input type="range" id="brightness"
       value="70" min="0" max="100"
       data-highlight="true">

迷你滑块

data-mini=true 渲染更小、更紧凑的滑块,占用更少的垂直空间——在设置面板中分组多个控件时很方便。其行为与常规滑块相同,只是尺寸更小。

jquery-mobile
<label for="age">Age</label>
<input type="range" id="age" value="25" min="0" max="120"
       data-mini="true" data-highlight="true">

步长与多个滑块

step 控制增量(例如 step=5 吸附到 0、5、10……)。每个 range 输入都是独立的滑块;若需双滑块范围,必须构建自定义组件或使用第三方插件。原生 value、min、max 属性驱动其行为。

jquery-mobile
<label for="temp">Temperature (step 5)</label>
<input type="range" id="temp" value="20" min="0" max="100" step="5">

<!-- Two independent sliders -->
<label for="low">Min</label>
<input type="range" id="low" value="10" min="0" max="100">
<label for="high">Max</label>
<input type="range" id="high" value="90" min="0" max="100">

滑块事件

滑块在用户开始拖动滑块时触发 slidestart,在拖动结束时触发 slidestop。要在拖动期间持续更新,可绑定底层 range 输入的原生 'input' 或 'change' 事件。用 $(el).val() 读取/写入值。

jquery-mobile
<label for="vol">Volume</label>
<input type="range" id="vol" value="50" min="0" max="100">

<script>
$("#vol").on("slidestart", function () {
  console.log("User started dragging");
});
$("#vol").on("slidestop", function () {
  console.log("Value is now " + $(this).val());
});
</script>
09

翻转开关

基础翻转开关

翻转开关是一个 <select>,恰好包含两个 <option> 元素并带有 data-role=slider。它渲染为 iOS 风格的开/关切换。选中的 option 决定初始状态,其值像普通 select 一样提交(所选 option 的值)。

jquery-mobile
<label for="notify">Notifications</label>
<select name="notify" id="notify" data-role="slider">
  <option value="off">Off</option>
  <option value="on" selected>On</option>
</select>

自定义标签

两个 option 的文本成为开关两侧的标签。可使用任何简短文本(开/关、是/否、启用/禁用)。保持标签简短,以便在小屏幕上不截断地显示在切换框内。

jquery-mobile
<label for="wifi">Wi-Fi</label>
<select id="wifi" data-role="slider">
  <option value="disabled">Disabled</option>
  <option value="enabled" selected>Enabled</option>
</select>

迷你翻转开关

data-mini=true 渲染更小的翻转开关,占用更少垂直空间,与迷你滑块和其他迷你控件匹配。在密集的设置面板中将迷你控件配对使用,以获得一致的紧凑外观。

jquery-mobile
<label for="sync">Auto-sync</label>
<select id="sync" data-role="slider" data-mini="true">
  <option value="no">No</option>
  <option value="yes" selected>Yes</option>
</select>

翻转开关主题

data-theme 设置开关滑块的颜色,data-track-theme 设置其后轨道的颜色。混用色板(例如浅色轨道上的深色滑块)可使激活状态在视觉上更明显。

jquery-mobile
<label for="darkmode">Dark mode</label>
<select id="darkmode" data-role="slider"
        data-theme="b" data-track-theme="a">
  <option value="off">Off</option>
  <option value="on" selected>On</option>
</select>

编程式切换

用 $(el).val(value) 设置值,然后调用 .slider('refresh') 更新视觉切换以匹配。用 .val() 读取当前状态。以编程方式更改底层 select 的值后,务必刷新,否则滑块不会移动。

jquery-mobile
<select id="power" data-role="slider">
  <option value="off">Off</option>
  <option value="on">On</option>
</select>

<script>
// Turn the switch on programmatically
$("#power").val("on").slider("refresh");
// Read current state
var state = $("#power").val(); // "on" or "off"
</script>
10

复选框与单选框

复选框

复选框是普通的 <input type=checkbox>,由 <label for=id> 包裹(或相邻)。jQuery Mobile 将 label 样式化为可点击的块。当 label 包裹 input 时,for 属性是可选的。选中状态如常随表单提交。

jquery-mobile
<label for="agree"><input type="checkbox" id="agree" name="agree"> I agree</label>

<label for="news"><input type="checkbox" id="news" name="news" checked> Newsletter</label>

<!-- Wrap in ui-field-contain for layout -->
<div class="ui-field-contain">
  <label for="agree">I agree to terms</label>
  <input type="checkbox" id="agree">
</div>

单选按钮

通过给单选框相同的 name 属性进行分组。将组包裹在 data-role=controlgroup 的 fieldset 中(带 <legend>),以共享圆角在视觉上聚为一组。同名组中一次只能选中一个单选框。

jquery-mobile
<fieldset data-role="controlgroup">
  <legend>Choose a color:</legend>
  <label for="r"><input type="radio" name="color" id="r" value="red" checked> Red</label>
  <label for="g"><input type="radio" name="color" id="g" value="green"> Green</label>
  <label for="b"><input type="radio" name="color" id="b" value="blue"> Blue</label>
</fieldset>

水平控件组

data-type=horizontal 将复选框或单选框排成单行,作为分段控件而非垂直堆叠。这很紧凑,适合简短标签(S/M/L、是/否)。保持标签简短以便在窄屏上显示。

jquery-mobile
<fieldset data-role="controlgroup" data-type="horizontal">
  <legend>Size:</legend>
  <label for="s"><input type="radio" name="size" id="s" value="s" checked> S</label>
  <label for="m"><input type="radio" name="size" id="m" value="m"> M</label>
  <label for="l"><input type="radio" name="size" id="l" value="l"> L</label>
</fieldset>

迷你与主题

data-mini=true 缩小控件,data-theme 设置项目选中/激活时应用的色板。为激活状态设置主题以突出于页面背景。这些选项一次应用于整个 controlgroup。

jquery-mobile
<fieldset data-role="controlgroup" data-mini="true" data-theme="b">
  <label for="a"><input type="checkbox" id="a"> Option A</label>
  <label for="b"><input type="checkbox" id="b"> Option B</label>
</fieldset>

修改后刷新

在代码中设置复选框/单选框的 checked 属性后,调用 .checkboxradio('refresh') 使增强后的视觉匹配。如果在运行时在 controlgroup 内添加或删除输入,调用 .controlgroup('refresh') 重新应用分组样式。

jquery-mobile
<input type="checkbox" id="c1">

<script>
// Check programmatically and update the visual state
$("#c1").prop("checked", true).checkboxradio("refresh");

// For a controlgroup, refresh the group after adding/removing items
$("#grp").controlgroup("refresh");
</script>
11

选择菜单

原生选择菜单

默认情况下 jQuery Mobile 显示自定义样式的 select,但底层仍打开系统选择器。设置 data-native-menu=true(或 data-role=none)可完全使用设备原生下拉——更快、更熟悉,但跨平台视觉一致性较差。

jquery-mobile
<label for="country">Country</label>
<select id="country" data-native-menu="true">
  <option value="us">United States</option>
  <option value="ca">Canada</option>
  <option value="uk">United Kingdom</option>
</select>

<!-- data-role="none" also keeps it fully native -->
<select data-role="none">...</select>

自定义选择菜单

data-native-menu=false 打开 jQuery Mobile 样式的弹出菜单而非原生选择器,在所有设备上提供一致外观。在手机上它显示为带“完成”按钮的全屏对话框;在平板上显示为字段附近较小的弹出框。

jquery-mobile
<label for="fruit">Fruit</label>
<select id="fruit" data-native-menu="false">
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="cherry">Cherry</option>
</select>

占位项与多选

空值的第一个 option 作为占位符。data-overlay-theme 设置自定义菜单的背景色。添加 multiple 属性可将自定义菜单变为复选清单对话框,用户可选择多个选项,在按钮上以逗号分隔显示。

jquery-mobile
<label for="color">Color</label>
<select id="color" data-native-menu="false" data-overlay-theme="b">
  <option value="">Choose a color...</option>
  <option value="red">Red</option>
  <option value="green">Green</option>
</select>

<!-- Multiple selection (renders as a checklist dialog) -->
<label for="tags">Tags</label>
<select id="tags" multiple data-native-menu="false">
  <option value="a">A</option>
  <option value="b">B</option>
</select>

选择菜单主题与遮罩

data-theme 设置 select 按钮本身的样式;data-overlay-theme 设置弹出框/背景色;data-divider-theme 设置菜单内任何 list-divider 分隔符的颜色。可在 option 之间插入 <li data-role=list-divider> 元素以在视觉上分组。

jquery-mobile
<label for="size">Size</label>
<select id="size" data-native-menu="false"
        data-theme="a" data-overlay-theme="b" data-divider-theme="a">
  <option value="s">Small</option>
  <option value="m">Medium</option>
  <li data-role="list-divider">Large sizes</li>
  <option value="l">Large</option>
</select>

选择菜单事件

监听标准的 'change' 事件以响应选择。在代码中更改值(或替换 option)后,调用 .selectmenu('refresh') 使按钮标签更新以匹配新选择。用 'refresh' 重建菜单,而非重新初始化。

jquery-mobile
<label for="city">City</label>
<select id="city" data-native-menu="false">
  <option value="ny">New York</option>
  <option value="la">Los Angeles</option>
</select>

<script>
$("#city").on("change", function () {
  console.log("Selected: " + $(this).val());
});
// Update options then refresh
$("#city").val("la").selectmenu("refresh");
</script>
12

弹出框

基础弹出框

弹出框是带有 data-role=popup 的 div。通过用 data-rel=popup 链接到其 id 来打开它。弹出框默认居中覆盖页面。添加 ui-content 获得内边距,并在内部链接上使用 data-rel=back 来关闭它。

jquery-mobile
<a href="#myPopup" data-rel="popup" class="ui-btn">Open popup</a>

<div data-role="popup" id="myPopup" class="ui-content">
  <p>This is a popup.</p>
  <a href="#" class="ui-btn" data-rel="back">Close</a>
</div>

弹出框过渡

在打开链接上(或弹出框本身上)使用 data-transition 选择动画。pop 和 fade 对弹出框最自然。页面使用的同一过渡集在此也适用;关闭操作会自动反向播放过渡。

jquery-mobile
<a href="#p" data-rel="popup" data-transition="pop">Pop</a>
<a href="#p" data-rel="popup" data-transition="fade">Fade</a>
<a href="#p" data-rel="popup" data-transition="slidedown">Slide down</a>

<div data-role="popup" id="p" class="ui-content" data-theme="a">
  <p>Transitioned in.</p>
</div>

弹出框定位

data-position-to 控制弹出框出现的位置:'origin'(打开它的元素,默认)、'#someId'(特定元素)或 'window'(屏幕居中)。以编程方式打开时也可传入 x/y 坐标:popup('open', x, y)。

jquery-mobile
<!-- Position relative to an element / coordinates -->
<a href="#tip" data-rel="popup" data-position-to="origin">Tip (on the link)</a>
<a href="#tip" data-rel="popup" data-position-to="#target">Tip (on #target)</a>
<a href="#tip" data-rel="popup" data-position-to="window">Centered</a>

<div data-role="popup" id="tip" class="ui-content">
  <p>Positioned popup.</p>
</div>

弹出菜单与工具提示

弹出框可包含任何内容——listview 成为上下文菜单,段落成为工具提示。用 data-theme 设置弹出框样式,内部内容用各自的主题。用户点击外部时弹出框自动关闭(除非 data-dismissible=false)。

jquery-mobile
<a href="#menu" data-rel="popup" class="ui-btn">Menu</a>
<div data-role="popup" id="menu" data-theme="b">
  <ul data-role="listview" data-inset="true" data-theme="d">
    <li data-role="divider">Actions</li>
    <li><a href="#">Edit</a></li>
    <li><a href="#">Share</a></li>
    <li><a href="#">Delete</a></li>
  </ul>
</div>

对话框弹出框

定位在窗口中心并带关闭按钮的弹出框可作为模态对话框。在角落添加 X 按钮(ui-icon-delete 配 ui-btn-icon-notext)。用 max-width 样式约束宽度以获得真正的对话框外观,而非全宽底部表单。

jquery-mobile
<a href="#dlg" data-rel="popup" data-position-to="window"
   data-transition="pop" class="ui-btn">Open dialog</a>

<div data-role="popup" id="dlg" data-theme="a" class="ui-content"
     style="max-width:400px;">
  <a href="#" data-rel="back" class="ui-btn ui-corner-all ui-icon-delete
     ui-btn-icon-notext ui-btn-right">Close</a>
  <h3>Confirm</h3>
  <p>Are you sure?</p>
  <a href="#" class="ui-btn ui-btn-b" data-rel="back">Yes</a>
  <a href="#" class="ui-btn" data-rel="back">No</a>
</div>

编程式打开与可关闭

用 .popup('open'/'close') 从代码打开或关闭弹出框。data-dismissible=false 阻止点击外部关闭,强制用户使用关闭按钮——适用于必须确认的场景。打开时可传入 x/y 坐标或位置对象。

jquery-mobile
<div data-role="popup" id="p2" data-dismissible="false">
  <p>Cannot close by tapping outside.</p>
  <a href="#" class="ui-btn" data-rel="back">Close</a>
</div>

<script>
// Open programmatically (optionally at coordinates)
$("#p2").popup("open");
$("#p2").popup("open", { x: 100, y: 200 });
// Close programmatically
$("#p2").popup("close");
</script>
13

面板

基础面板

面板是带有 data-role=panel 的 div,放在页面内(通常在页眉之前)。通过按钮链接到其 id 来打开。在内部链接上使用 data-rel=close 关闭面板。面板非常适合滑出式导航菜单。

jquery-mobile
<div data-role="page" id="home">
  <div data-role="panel" id="myPanel">
    <h2>Menu</h2>
    <p>Panel content here.</p>
    <a href="#" class="ui-btn" data-rel="close">Close</a>
  </div>

  <div data-role="header">
    <a href="#myPanel" class="ui-btn ui-btn-inline ui-corner-all ui-icon-bars ui-btn-icon-notext">Menu</a>
    <h1>Home</h1>
  </div>
  <div data-role="main" class="ui-content">
    <p>Page content.</p>
  </div>
</div>

面板显示模式

data-display 控制打开动画:'reveal'(默认)滑开页面以露出下方的面板;'overlay' 将面板滑到页面之上;'push' 将面板滑入并将页面推过。菜单最常用 overlay。

jquery-mobile
<div data-role="panel" id="p1" data-display="reveal">Reveal</div>
<div data-role="panel" id="p2" data-display="overlay">Overlay</div>
<div data-role="panel" id="p3" data-display="push">Push</div>

<!-- data-display controls how the panel interacts with the page:
     reveal : panel sits under the page, page slides away
     overlay: panel slides over the page (page stays)
     push   : both panel and page slide -->

面板位置

data-position=left(默认)或 right 设置面板从哪一侧滑入。同一页面可同时有左侧和右侧面板。一次只能打开一个面板;打开第二个会关闭第一个。

jquery-mobile
<!-- Left panel (default) -->
<div data-role="panel" id="leftP" data-position="left">Left</div>

<!-- Right panel -->
<div data-role="panel" id="rightP" data-position="right">Right</div>

<a href="#leftP" class="ui-btn">Open left</a>
<a href="#rightP" class="ui-btn">Open right</a>

可关闭与滑动

data-dismissible=true(默认)在用户点击外部时关闭面板。data-swipe-close=true 允许用户向相反方向滑动来关闭它(例如向右滑动关闭左侧面板)。overlay 面板默认两者都开启。

jquery-mobile
<div data-role="panel" id="p"
     data-dismissible="true"
     data-swipe-close="true"
     data-position="left"
     data-display="overlay">
  <p>Tap outside or swipe to close.</p>
</div>

面板事件

面板触发 panelbeforeopen、panelopen、panelbeforeclose 和 panelclose 事件。从 'before' 处理函数返回 false 可取消操作——适用于关闭前确认。用 .panel('open'/'close') 从代码打开/关闭。

jquery-mobile
<div data-role="panel" id="p">...</div>

<script>
$("#p").on("panelopen", function () {
  console.log("Panel opened");
});
$("#p").on("panelbeforeclose", function () {
  // return false here to prevent closing
  console.log("About to close");
});
$("#p").on("panelclose", function () {
  console.log("Panel closed");
});

// Open / close programmatically
$("#p").panel("open");
$("#p").panel("close");
</script>
14

可折叠组件

基础可折叠

带有 data-role=collapsible 的 div 将标题(h1-h6)作为可点击的标题,其余作为可展开内容。默认折叠。点击标题可切换内容的展开/折叠,带 +/- 图标。

jquery-mobile
<div data-role="collapsible">
  <h3>Section title</h3>
  <p>Hidden content shown when expanded.</p>
  <p>Click the header to toggle.</p>
</div>

可折叠图标与主题

用 data-collapsed-icon 和 data-expanded-icon 自定义指示图标(默认加/减)。data-theme 设置标题样式;data-content-theme 设置展开内容区样式。data-collapsed=false 使分区初始展开而非折叠。

jquery-mobile
<div data-role="collapsible"
     data-collapsed-icon="carat-r"
     data-expanded-icon="carat-d"
     data-theme="b" data-content-theme="a"
     data-collapsed="false">
  <h3>Initially open</h3>
  <p>Custom icons and theme.</p>
</div>

可折叠集合(手风琴)

collapsibleset 将可折叠组件分组,使一次只展开一个——手风琴。展开一个会自动关闭其他。(在 1.4 中属性为 data-role=collapsibleset;旧的 collapsible-set 名称仍然有效。)整个集合共享统一主题。

jquery-mobile
<div data-role="collapsibleset" data-theme="a" data-content-theme="a">
  <div data-role="collapsible">
    <h3>Section 1</h3>
    <p>Only one section open at a time.</p>
  </div>
  <div data-role="collapsible" data-collapsed="false">
    <h3>Section 2 (open by default)</h3>
    <p>Opening this closes Section 1.</p>
  </div>
  <div data-role="collapsible">
    <h3>Section 3</h3>
    <p>Third section.</p>
  </div>
</div>

预展开与内嵌

在 collapsibleset 中,在希望初始展开的分区上设置 data-collapsed=false。data-inset=true(集合默认)为组添加圆角和外边距。边缘到边缘集合使用 data-inset=false 跨越全宽。

jquery-mobile
<!-- A set always starts with one open by default; control with data-collapsed -->
<div data-role="collapsibleset" data-inset="true">
  <div data-role="collapsible" data-collapsed="false">
    <h3>Open first</h3>
    <p>Content</p>
  </div>
  <div data-role="collapsible">
    <h3>Closed second</h3>
    <p>Content</p>
  </div>
</div>

带列表视图的可折叠

可折叠组件可包含任何组件,包括 listview。这是在可折叠标题下分组长列表的好模式。为可折叠组件添加 data-filter=true 可通过标题区内的搜索框过滤内部 listview 的项目。

jquery-mobile
<div data-role="collapsible" data-filter="true">
  <h3>Contacts</h3>
  <ul data-role="listview">
    <li><a href="#">Alice</a></li>
    <li><a href="#">Bob</a></li>
    <li><a href="#">Carol</a></li>
  </ul>
</div>

编程式展开/折叠

用 .collapsible('expand') 和 .collapsible('collapse') 从代码控制可折叠组件。监听 'collapse' 和 'expand' 事件以响应用户切换。对于集合,以编程方式展开一个分区会自动折叠其他分区。

jquery-mobile
<div data-role="collapsible" id="c">
  <h3>Section</h3>
  <p>Content</p>
</div>

<script>
// Expand or collapse from code
$("#c").collapsible("expand");
$("#c").collapsible("collapse");
// Toggle based on current state
$("#c h3").click(); // simplest manual toggle
</script>
15

选项卡

基础选项卡

tabs 组件是带有 data-role=tabs 的 div,包含 navbar(选项卡链接)和 id 与链接 href 匹配的内容面板。带 ui-btn-active 的链接首先显示。点击选项卡显示其面板并隐藏其他——无页面过渡。

jquery-mobile
<div data-role="tabs" id="myTabs">
  <div data-role="navbar">
    <ul>
      <li><a href="#tab1" class="ui-btn-active">One</a></li>
      <li><a href="#tab2">Two</a></li>
      <li><a href="#tab3">Three</a></li>
    </ul>
  </div>
  <div id="tab1" class="ui-body-d ui-content">Content 1</div>
  <div id="tab2" class="ui-body-d ui-content">Content 2</div>
  <div id="tab3" class="ui-body-d ui-content">Content 3</div>
</div>

带图标的选项卡

为选项卡链接添加 ui-icon-{name} 和 ui-btn-icon-top 类可在标签上方显示图标,提供应用式的标签栏。活动选项卡保留 ui-btn-active。使用 ui-btn-icon-top 使图标位于选项卡条中的文本上方。

jquery-mobile
<div data-role="tabs">
  <div data-role="navbar">
    <ul>
      <li><a href="#t1" class="ui-btn-active ui-icon-home ui-btn-icon-top">Home</a></li>
      <li><a href="#t2" class="ui-icon-search ui-btn-icon-top">Search</a></li>
      <li><a href="#t3" class="ui-icon-gear ui-btn-icon-top">Settings</a></li>
    </ul>
  </div>
  <div id="t1" class="ui-content">Home tab</div>
  <div id="t2" class="ui-content">Search tab</div>
  <div id="t3" class="ui-content">Settings tab</div>
</div>

AJAX 选项卡

当选项卡链接的 href 是 URL(非 #id)时,tabs 组件会在激活时通过 AJAX 将该页面加载到容器中。页面初始化时自动加载第一个选项卡。这适用于按选项卡懒加载重型内容。

jquery-mobile
<div data-role="tabs">
  <div data-role="navbar">
    <ul>
      <li><a href="ajax-tab1.html" class="ui-btn-active">One</a></li>
      <li><a href="ajax-tab2.html">Two</a></li>
    </ul>
  </div>
  <!-- The first tab's content is loaded into this container -->
  <div class="ui-content" id="ajax-content"></div>
</div>

选项卡持久化

选项卡默认不会在重新加载后记住其活动状态。使用 tabsactivate 事件(提供 ui.newPanel/ui.oldPanel)加 localStorage 来持久化选择。加载时重新触发保存的选项卡的 click 以恢复它。

jquery-mobile
<div data-role="tabs" id="t">
  <div data-role="navbar">
    <ul>
      <li><a href="#a" class="ui-btn-active">A</a></li>
      <li><a href="#b">B</a></li>
    </ul>
  </div>
  <div id="a" class="ui-content">A</div>
  <div id="b" class="ui-content">B</div>
</div>

<script>
// Remember the active tab across reloads
var saved = localStorage.getItem("activeTab") || "#a";
$("#t a[href='" + saved + "']").click();
$("#t").on("tabsactivate", function (e, ui) {
  localStorage.setItem("activeTab", "#" + ui.newPanel.attr("id"));
});
</script>

选项卡事件

tabsbeforeactivate 在选项卡切换前触发(返回 false 取消);tabsactivate 在之后触发。两者都提供 ui.newTab/ui.oldTab(<a> 链接)和 ui.newPanel/ui.oldPanel(内容 div)。用它们来懒加载内容、记录分析或在切换前验证。

jquery-mobile
<div data-role="tabs" id="t">...</div>

<script>
$("#t").on("tabsbeforeactivate", function (e, ui) {
  // ui.newTab, ui.oldTab, ui.newPanel, ui.oldPanel
  // return false to cancel the switch
  console.log("Switching to", ui.newPanel.attr("id"));
});
$("#t").on("tabsactivate", function (e, ui) {
  console.log("Now showing", ui.newPanel.attr("id"));
});
</script>
16

主题

主题色板 (a-e)

jQuery Mobile 主题使用字母编号的‘色板’(a-e)而非单一颜色。a 是最高对比度(深色),是页眉/页脚的默认值;b 是蓝色强调色;c 是默认的浅色页面背景。用 data-theme 在任何元素上应用色板。

jquery-mobile
<!-- jQuery Mobile ships with 5 swatches: a, b, c, d, e -->
<!-- a = black (high contrast), b = blue, c = light gray,
     d = medium gray, e = yellow -->

<div data-role="page" data-theme="b">
  <div data-role="header" data-theme="a"><h1>Dark header</h1></div>
  <div data-role="main" class="ui-content">Page body</div>
  <div data-role="footer" data-theme="a"><h4>Dark footer</h4></div>
</div>

应用主题

按钮使用 ui-btn-{色板} 类(例如 ui-btn-b 为蓝色按钮)。其他元素使用 data-theme={色板}。子元素继承父元素的色板,除非显式设置。默认页面色板为 'c'(浅灰)。

jquery-mobile
<!-- Per element -->
<a href="#" class="ui-btn ui-btn-a">Swatch A button</a>
<a href="#" class="ui-btn ui-btn-b">Swatch B button</a>

<!-- On bars, lists, forms -->
<div data-role="header" data-theme="b">...</div>
<ul data-role="listview" data-theme="c">...</ul>
<input type="text" data-theme="b">

遮罩主题

data-overlay-theme 设置弹出框、对话框或自定义选择菜单背后暗色背景的颜色。遮罩使用深色色板(a 或 b)以使前景内容突出。弹出框自身的 data-theme 控制弹出框盒子的颜色。

jquery-mobile
<!-- Overlay theme for popups, dialogs, custom selects -->
<div data-role="popup" id="p" data-overlay-theme="b" data-theme="a"
     class="ui-content">
  <p>Dark backdrop, light popup.</p>
</div>

<a href="#p" data-rel="popup" data-transition="pop" class="ui-btn">Open</a>

列表与按钮主题

listview 接受独立的主题:data-theme 用于行,data-divider-theme 用于分隔符标题,data-count-theme 用于计数气泡。这可让你突出分隔符同时保持行柔和。同样的细粒度主题也适用于按钮和表单。

jquery-mobile
<ul data-role="listview" data-theme="d" data-divider-theme="b"
    data-count-theme="b" data-inset="true">
  <li data-role="list-divider">Group (swatch b)</li>
  <li><a href="#">Item (swatch d) <span class="ui-li-count">5</span></a></li>
</ul>

自定义色板

每个色板只是一组 CSS 类(.ui-bar-{x}、.ui-body-{x}、.ui-btn-up-{x} 等)。要添加自定义色板 'f',复制这些规则并重新着色——或使用 ThemeRoller 工具生成完整的自定义主题文件。然后用 data-theme=f 引用它。

jquery-mobile
/* Add a custom swatch 'f' by copying the .ui-bar-f, .ui-body-f,
   .ui-btn-up-f, .ui-btn-hover-f, .ui-btn-down-f rules and changing
   the colors. ThemeRoller generates these for you. */
.ui-bar-f { background: #6c2; color: #fff; }
.ui-body-f { background: #efe; color: #030; }
.ui-btn-up-f { background: #6c2; color: #fff; }
.ui-btn-hover-f { background: #5b1; color: #fff; }

<!-- Use it like any built-in swatch -->
<div data-role="header" data-theme="f"><h1>Green header</h1></div>

主题继承

元素未设置自身色板时继承最近祖先的色板。在较高层级(例如页面上)设置色板可统一主题化内部所有内容,然后按需覆盖单个元素。在 mobileinit 期间更改全局默认页面主题。

jquery-mobile
<div data-role="page" data-theme="b">
  <!-- Inherits swatch b unless overridden -->
  <div data-role="main" class="ui-content">
    <a href="#" class="ui-btn">Inherits b</a>
    <a href="#" class="ui-btn ui-btn-a">Explicit a</a>
    <a href="#" class="ui-btn" data-theme="a">Explicit a (attr)</a>
  </div>
</div>

<!-- Global default swatch -->
<script>
$(document).on("mobileinit", function () {
  $.mobile.page.prototype.options.theme = "b";
});
</script>
17

响应式布局

网格布局

网格是 CSS 类,而非组件。ui-grid-a 创建 2 列网格,ui-grid-b 为 3 列,直到 ui-grid-d(5 列)。子元素依次获得 ui-block-a、ui-block-b……并自动换行。网格始终 100% 宽,自身不响应断点。

jquery-mobile
<!-- 2-column grid (ui-grid-a) -->
<div class="ui-grid-a">
  <div class="ui-block-a"><div class="ui-bar">A</div></div>
  <div class="ui-block-b"><div class="ui-bar">B</div></div>
</div>

<!-- 3-column grid (ui-grid-b), 4 = ui-grid-c, 5 = ui-grid-d -->
<div class="ui-grid-b">
  <div class="ui-block-a">A</div>
  <div class="ui-block-b">B</div>
  <div class="ui-block-c">C</div>
</div>

响应式网格

jQuery Mobile 网格没有内置断点,但可添加自定义媒体查询:在窄宽度下将块设为 width:100% 和 float:none 使其垂直堆叠,在较宽屏幕上应用默认列。添加标记类以限定规则范围。

jquery-mobile
<style>
/* Stack grid columns on phones, side-by-side on tablets */
@media (max-width: 40em) {
  .ui-responsive .ui-block-a,
  .ui-responsive .ui-block-b { width: 100%; float: none; }
}
</style>

<div class="ui-grid-a ui-responsive">
  <div class="ui-block-a">Left (stacks on phone)</div>
  <div class="ui-block-b">Right (stacks on phone)</div>
</div>

回流表格

回流表格(data-mode=reflow)在窄屏上重组为堆叠的卡片布局,将每列的标题作为标签重复显示在其值旁边。添加 ui-responsive 类使回流仅在断点以下生效,在宽屏上保持普通表格。

jquery-mobile
<table data-role="table" data-mode="reflow" class="ui-responsive">
  <thead><tr><th>Name</th><th>Age</th><th>City</th></tr></thead>
  <tbody>
    <tr><td>Alice</td><td>30</td><td>NYC</td></tr>
    <tr><td>Bob</td><td>25</td><td>LA</td></tr>
  </tbody>
</table>

<!-- On narrow screens each cell shows its column header as a label -->

列切换表格

columntoggle 表格添加一个“列...”按钮,让用户选择显示哪些列。为可选列分配 data-priority=1..6(数字越小越重要,在更宽断点显示);无优先级的列始终显示。最重要的列在手机上保留;其余收入菜单。

jquery-mobile
<table data-role="table" data-mode="columntoggle"
       class="ui-responsive" id="tbl">
  <thead>
    <tr>
      <th data-priority="1">Rank</th>
      <th data-priority="2">Name</th>
      <th>Team</th>           <!-- priority 'persist' (always shown) -->
      <th data-priority="3">Points</th>
      <th data-priority="4">Wins</th>
    </tr>
  </thead>
  <tbody><tr><td>1</td><td>Alice</td><td>Red</td><td>100</td><td>10</td></tr></tbody>
</table>

断点与辅助类

jQuery Mobile 没有工具断点类;你需为自定义布局编写自己的媒体查询。内置的 40em(640px)断点仅控制响应式表格(ui-responsive)在堆叠和表格模式之间切换。对于网格和面板,用基于 em 的查询定义自己的断点。

jquery-mobile
<!-- jQuery Mobile doesn't ship breakpoint classes like Bootstrap,
     but you can combine media queries with jQM structure. -->

<style>
@media (min-width: 45em) { /* tablet+ */
  .split { width: 50%; float: left; box-sizing: border-box; padding: 0 .5em; }
}
</style>

<div class="split">Left panel</div>
<div class="split">Right panel</div>

<!-- ui-responsive class triggers table breakpoints at 40em (640px) -->
18

触摸事件

点击与长按

tap 在快速触摸时触发(比移动端 click 更快更可靠,后者有约 300ms 延迟)。taphold 在用户按住约 750ms 时触发。两者都经过规范化,可与鼠标和触摸一起工作,因此同一代码可在桌面和移动端运行。

jquery-mobile
<div id="box" class="ui-bar">Tap or hold me</div>

<script>
$("#box").on("tap", function () {
  $(this).css("background", "yellow");
});
$("#box").on("taphold", function () {
  $(this).css("background", "red");
});
</script>

滑动与滑动方向

swipe 在任何水平滑动时触发;swipeleft 和 swiperight 告诉你方向——适用于图片轮播或页面导航。它们基于水平移动;垂直滚动有意不被视为滑动,以便正常页面滚动仍可工作。

jquery-mobile
<div id="card" class="ui-bar">Swipe me</div>

<script>
$("#card").on("swipe", function () {
  console.log("Swiped in any direction");
});
$("#card").on("swipeleft", function () {
  $(this).text("Swiped left -> next");
});
$("#card").on("swiperight", function () {
  $(this).text("Swiped right -> prev");
});
</script>

滑动阈值

滑动仅在 horizontalDistanceThreshold(默认 30px)内、持续 durationThreshold(默认 1000ms)以内,且垂直方向不超过 verticalDistanceThreshold 时才触发。提高水平阈值可要求更长滑动;降低它可更灵敏。在 mobileinit 期间设置这些。

jquery-mobile
<script>
// Globally tune swipe sensitivity (bind before jQM loads)
$(document).on("mobileinit", function () {
  $.event.special.swipe.horizontalDistanceThreshold = 60; // px, default 30
  $.event.special.swipe.durationThreshold = 800;          // ms, default 1000
  $.event.special.swipe.verticalDistanceThreshold = 40;   // px, default 75
});
</script>

<script src="jquery.mobile-1.4.5.min.js"></script>

虚拟鼠标事件

vmouse* 事件是 jQuery Mobile 统一的鼠标/触摸/指针事件——无论用户使用手指还是鼠标,它们都一致触发。用 vclick 代替 click 可避免移动端 300ms 延迟。它们是 tap 和 swipe 的构建基础。

jquery-mobile
<script>
// vmouse events unify mouse + touch + pointer
$("#el").on("vmousedown", function () { /* finger down / mouse down */ });
$("#el").on("vmouseup",   function () { /* finger up / mouse up   */ });
$("#el").on("vmousemove", function () { /* drag                    */ });
$("#el").on("vmouseover", function () { /* hover-in (best-effort)  */ });
$("#el").on("vmouseout",  function () { /* hover-out (best-effort) */ });
$("#el").on("vclick",     function () { /* tap/click unified       */ });
</script>

方向变化

orientationchange 在设备旋转时触发,e.orientation 等于 'portrait' 或 'landscape'。将依赖布局的代码包裹在短时 setTimeout 中,因为视口尺寸在事件触发后略有更新。在无陀螺仪的设备上监听 'resize' 事件作为后备。

jquery-mobile
<script>
$(window).on("orientationchange", function (e) {
  // e.orientation is "portrait" or "landscape"
  console.log("Now " + e.orientation);
});

// React after the rotation finishes (layout is settled)
$(window).on("orientationchange", function (e) {
  setTimeout(function () {
    $("body").removeClass("portrait landscape").addClass(e.orientation);
  }, 300);
});
</script>

滚动与节流

scrollstart 和 scrollstop 是 jQuery Mobile 的节流滚动事件(浏览器原生节流滚动处理函数,但这些提供明确的开始/停止时刻)。要阻止元素上的滚动/缩放——例如绘图画布或地图——绑定 touchmove 并返回 false。

jquery-mobile
<script>
// scrollstart / scrollstop are throttled for performance
$(document).on("scrollstart", function () {
  $("#hint").hide();
});
$(document).on("scrollstop", function () {
  $("#hint").show();
});

// Silence touch scroll on a specific element
$("#canvas").on("touchmove", false);
</script>
19

页面事件与生命周期

页面初始化事件

pagebeforecreate 在 jQuery Mobile 增强页面标记之前触发——注入类或组件以便它们也被增强的最佳位置。pagecreate 在增强完成后立即触发——用它绑定事件处理函数和初始化插件。每个事件每页触发一次。

jquery-mobile
<div data-role="page" id="home">
  <div data-role="main" class="ui-content">
    <a href="#second" class="ui-btn">Go to second</a>
  </div>
</div>

<script>
$(document).on("pagebeforecreate", "#home", function () {
  // Before enhancement — good place to add classes/widgets
});
$(document).on("pagecreate", "#home", function () {
  // After enhancement, before show — bind widgets here
  console.log("Home page created");
});
</script>

页面显示与隐藏

pagebeforeshow/pageshow 在页面可见之前/之后触发;pagebeforehide/pagehide 在其隐藏之前/之后触发。'show' 事件在每次显示页面时触发(不止一次),因此它们是返回页面时刷新动态数据的正确位置。

jquery-mobile
<script>
$(document).on("pagebeforeshow", "#home", function () {
  console.log("About to show home");
});
$(document).on("pageshow", "#home", function () {
  console.log("Home shown (transition done)");
});
$(document).on("pagebeforehide", "#home", function () {
  console.log("About to leave home");
});
$(document).on("pagehide", "#home", function () {
  console.log("Home hidden");
});
</script>

页面变更前

pagebeforechange 在任何导航之前触发,是拦截或重定向它的位置(调用 preventDefault 取消)。pagechange 在成功导航后触发;pagechangefailed 在加载目标页面出错时触发。这些对内部(#id)和 AJAX 导航都触发。

jquery-mobile
<script>
$(document).on("pagebeforechange", function (e, data) {
  // data.toPage is the target (URL string or jQuery object)
  // data.options has transition, reverse, etc.
  // return false (or e.preventDefault()) to cancel navigation
  if (typeof data.toPage === "string" && data.toPage.indexOf("block") > -1) {
    e.preventDefault();
    alert("Blocked");
  }
});
$(document).on("pagechange", function (e, data) {
  console.log("Navigation completed");
});
$(document).on("pagechangefailed", function (e, data) {
  console.log("Navigation failed");
});
</script>

页面容器加载

pageload 在通过 AJAX 获取的页面成功插入 DOM 时触发(提供 data.url 和 data.page)。pageloadfailed 在加载错误时触发——默认 jQM 显示错误消息;从处理函数返回 false 告诉 jQM 你已自行处理。

jquery-mobile
<script>
// Fires when a page is loaded via AJAX into the DOM
$(document).on("pageload", function (e, data) {
  console.log("Loaded: " + data.url);
  console.log("Page obj:", data.page);
});
$(document).on("pageloadfailed", function (e, data) {
  // return false to let jQM show its default error message
  console.log("Failed to load: " + data.url);
});
</script>

绑定页面事件

用 document 上的事件委托绑定页面事件,按页面的 #id 选择器过滤——这甚至适用于稍后通过 AJAX 拉入的页面。对于编程式导航,使用 pagecontainer 组件的 'change' 方法($.mobile.changePage 的现代替代),传入目标和选项。

jquery-mobile
<script>
// Delegate by page id — works for AJAX-loaded pages too
$(document).on("pagecreate", "#settings", function () {
  var page = $(this);
  page.find("#save").on("tap", function () {
    alert("Saved settings");
  });
});

// Use the pagecontainer widget (1.4+) for programmatic navigation
$(":mobile-pagecontainer").pagecontainer("change", "#settings", {
  transition: "slide",
  reverse: false
});
</script>

页面移除与清理

默认情况下,导航离开后 jQuery Mobile 会从 DOM 中移除该页面(除非 domCache 开启)。pageremove 在移除之前触发——在此清理定时器、监听器或插件实例。pagehide 事件的 ui.prevPage 提供刚隐藏页面的 jQuery 对象以进行清理。

jquery-mobile
<script>
// Fires when a page is removed from the DOM (default behavior for
// non-cached pages after navigation away)
$(document).on("pageremove", function (e, ui) {
  console.log("Page removed from DOM:", ui.prevPage);
});

// Clean up resources when a page is hidden for good
$(document).on("pagehide", "#temp", function () {
  clearInterval($(this).data("timer"));
});
</script>

这篇内容对您有帮助吗?

学习路径

从零开始学习

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