简体中文 繁體中文 English 日本語 Deutsch 한국 사람 بالعربية TÜRKÇE português คนไทย Français

站内搜索

搜索

活动公告

11-02 12:46
10-23 09:32
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,将及时处理!
10-23 09:31
10-23 09:28
通知:签到时间调整为每日4:00(东八区)
10-23 09:26

jQuery UI状态条完整教程从基础概念到高级应用轻松掌握网页进度条组件的开发技巧和最佳实践

3万

主题

349

科技点

3万

积分

大区版主

木柜子打湿

积分
31898

三倍冰淇淋无人之境【一阶】财Doro小樱(小丑装)立华奏以外的星空【二阶】⑨的冰沙

发表于 2025-9-10 01:50:13 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1. jQuery UI进度条组件简介

jQuery UI进度条(Progressbar)是一个强大的用户界面组件,用于显示任务完成的百分比或进度状态。它是jQuery UI库的一部分,提供了丰富的自定义选项和事件处理机制,使开发者能够轻松创建各种风格的进度指示器。

进度条在网页应用中非常常见,例如文件上传、表单提交、数据处理等需要一定时间的操作中,进度条可以直观地向用户展示当前操作的完成情况,提升用户体验。

1.1 为什么使用jQuery UI进度条

使用jQuery UI进度条有以下几个主要优势:

• 易于实现:只需几行代码即可创建功能完整的进度条
• 高度可定制:支持自定义样式、动画和主题
• 跨浏览器兼容:在主流浏览器中表现一致
• 丰富的API:提供多种方法和事件,便于控制和交互
• 无障碍支持:遵循WAI-ARIA标准,支持屏幕阅读器

1.2 准备工作

在使用jQuery UI进度条之前,需要确保页面中引入了必要的文件:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>jQuery UI进度条教程</title>
  7.    
  8.     <!-- jQuery库 -->
  9.     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  10.    
  11.     <!-- jQuery UI库 -->
  12.     <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  13.    
  14.     <!-- jQuery UI CSS -->
  15.     <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
  16.    
  17.     <style>
  18.         /* 自定义样式将在这里添加 */
  19.         .container {
  20.             width: 80%;
  21.             margin: 50px auto;
  22.             padding: 20px;
  23.         }
  24.         .custom-progress {
  25.             margin-top: 20px;
  26.         }
  27.     </style>
  28. </head>
  29. <body>
  30.     <div class="container">
  31.         <h1>jQuery UI进度条示例</h1>
  32.         
  33.         <!-- 进度条将在这里添加 -->
  34.         <div id="progressbar"></div>
  35.         
  36.         <!-- 其他内容 -->
  37.     </div>
  38.    
  39.     <script>
  40.         // jQuery代码将在这里添加
  41.     </script>
  42. </body>
  43. </html>
复制代码

2. 基础进度条创建

2.1 创建基本进度条

创建一个基本的jQuery UI进度条非常简单,只需选择一个元素并调用.progressbar()方法:
  1. $(document).ready(function() {
  2.     $("#progressbar").progressbar({
  3.         value: 37 // 设置初始值为37%
  4.     });
  5. });
复制代码

这段代码会将ID为progressbar的div元素转换为一个进度条,并设置初始值为37%。

2.2 动态更新进度条

进度条的值可以通过JavaScript动态更新。以下是一个模拟进度增加的示例:
  1. $(document).ready(function() {
  2.     let progressbar = $("#progressbar");
  3.    
  4.     // 初始化进度条
  5.     progressbar.progressbar({
  6.         value: 0
  7.     });
  8.    
  9.     // 模拟进度增加
  10.     function updateProgress() {
  11.         let value = progressbar.progressbar("value") || 0;
  12.         
  13.         if (value < 100) {
  14.             value += 1;
  15.             progressbar.progressbar("value", value);
  16.             setTimeout(updateProgress, 100);
  17.         }
  18.     }
  19.    
  20.     // 开始进度更新
  21.     setTimeout(updateProgress, 1000);
  22. });
复制代码

在这个示例中,我们首先初始化进度条值为0,然后定义一个updateProgress函数,每次调用将进度值增加1,直到达到100%。使用setTimeout函数来模拟异步操作中的进度更新。

2.3 获取进度条当前值

要获取进度条的当前值,可以使用以下方法:
  1. let currentValue = $("#progressbar").progressbar("value");
  2. console.log("当前进度值: " + currentValue + "%");
复制代码

3. 进度条配置选项

jQuery UI进度条提供了多种配置选项,允许开发者自定义进度条的外观和行为。

3.1 常用配置选项

value选项用于设置或获取进度条的当前值,范围从0到100。
  1. $("#progressbar").progressbar({
  2.     value: 50 // 设置初始值为50%
  3. });
复制代码

disabled选项用于禁用或启用进度条。
  1. $("#progressbar").progressbar({
  2.     value: 50,
  3.     disabled: true // 禁用进度条
  4. });
  5. // 启用进度条
  6. $("#progressbar").progressbar("option", "disabled", false);
复制代码

max选项用于设置进度条的最大值,默认为100。
  1. $("#progressbar").progressbar({
  2.     value: 50,
  3.     max: 200 // 设置最大值为200
  4. });
  5. // 更新进度值
  6. $("#progressbar").progressbar("value", 100); // 现在显示为50%,因为100是200的一半
复制代码

3.2 完整配置示例

下面是一个使用多种配置选项的完整示例:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>jQuery UI进度条配置示例</title>
  7.     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8.     <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  9.     <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
  10.     <style>
  11.         .container {
  12.             width: 80%;
  13.             margin: 50px auto;
  14.             padding: 20px;
  15.         }
  16.         .controls {
  17.             margin-top: 20px;
  18.         }
  19.         button {
  20.             margin-right: 10px;
  21.             padding: 5px 10px;
  22.         }
  23.         #progress-value {
  24.             margin-left: 10px;
  25.             font-weight: bold;
  26.         }
  27.     </style>
  28. </head>
  29. <body>
  30.     <div class="container">
  31.         <h1>jQuery UI进度条配置示例</h1>
  32.         
  33.         <div id="progressbar"></div>
  34.         <div>当前进度: <span id="progress-value">0</span>%</div>
  35.         
  36.         <div class="controls">
  37.             <button id="start-btn">开始</button>
  38.             <button id="pause-btn">暂停</button>
  39.             <button id="reset-btn">重置</button>
  40.             <button id="disable-btn">禁用/启用</button>
  41.         </div>
  42.     </div>
  43.    
  44.     <script>
  45.         $(document).ready(function() {
  46.             let progressTimer;
  47.             let progressbar = $("#progressbar");
  48.             let progressValue = $("#progress-value");
  49.             
  50.             // 初始化进度条
  51.             progressbar.progressbar({
  52.                 value: 0,
  53.                 max: 100,
  54.                 disabled: false,
  55.                 change: function() {
  56.                     // 当值改变时更新显示
  57.                     progressValue.text(progressbar.progressbar("value"));
  58.                 },
  59.                 complete: function() {
  60.                     // 当完成时清除定时器
  61.                     clearInterval(progressTimer);
  62.                     alert("进度完成!");
  63.                 }
  64.             });
  65.             
  66.             // 开始按钮点击事件
  67.             $("#start-btn").click(function() {
  68.                 if (!progressTimer) {
  69.                     progressTimer = setInterval(function() {
  70.                         let value = progressbar.progressbar("value") || 0;
  71.                         if (value < 100) {
  72.                             progressbar.progressbar("value", value + 1);
  73.                         } else {
  74.                             clearInterval(progressTimer);
  75.                             progressTimer = null;
  76.                         }
  77.                     }, 100);
  78.                 }
  79.             });
  80.             
  81.             // 暂停按钮点击事件
  82.             $("#pause-btn").click(function() {
  83.                 clearInterval(progressTimer);
  84.                 progressTimer = null;
  85.             });
  86.             
  87.             // 重置按钮点击事件
  88.             $("#reset-btn").click(function() {
  89.                 clearInterval(progressTimer);
  90.                 progressTimer = null;
  91.                 progressbar.progressbar("value", 0);
  92.             });
  93.             
  94.             // 禁用/启用按钮点击事件
  95.             $("#disable-btn").click(function() {
  96.                 let isDisabled = progressbar.progressbar("option", "disabled");
  97.                 progressbar.progressbar("option", "disabled", !isDisabled);
  98.                 $(this).text(isDisabled ? "禁用" : "启用");
  99.             });
  100.         });
  101.     </script>
  102. </body>
  103. </html>
复制代码

4. 进度条事件处理

jQuery UI进度条提供了多种事件,使开发者能够对进度条的状态变化做出响应。

4.1 可用事件

当进度条被创建时触发。
  1. $("#progressbar").progressbar({
  2.     value: 50,
  3.     create: function(event, ui) {
  4.         console.log("进度条已创建");
  5.     }
  6. });
复制代码

当进度条的值发生变化时触发。
  1. $("#progressbar").progressbar({
  2.     value: 0,
  3.     change: function(event, ui) {
  4.         let value = $(this).progressbar("value");
  5.         console.log("进度已更改为: " + value + "%");
  6.     }
  7. });
复制代码

当进度条的值达到最大值时触发。
  1. $("#progressbar").progressbar({
  2.     value: 0,
  3.     complete: function(event, ui) {
  4.         console.log("进度已完成!");
  5.         alert("任务完成!");
  6.     }
  7. });
复制代码

4.2 事件处理示例

下面是一个综合使用各种事件的示例:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>jQuery UI进度条事件示例</title>
  7.     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8.     <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  9.     <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
  10.     <style>
  11.         .container {
  12.             width: 80%;
  13.             margin: 50px auto;
  14.             padding: 20px;
  15.         }
  16.         .event-log {
  17.             margin-top: 20px;
  18.             padding: 10px;
  19.             border: 1px solid #ddd;
  20.             height: 200px;
  21.             overflow-y: auto;
  22.             background-color: #f9f9f9;
  23.         }
  24.         .log-entry {
  25.             margin-bottom: 5px;
  26.             padding: 5px;
  27.             border-bottom: 1px solid #eee;
  28.         }
  29.         .controls {
  30.             margin-top: 20px;
  31.         }
  32.         button {
  33.             margin-right: 10px;
  34.             padding: 5px 10px;
  35.         }
  36.     </style>
  37. </head>
  38. <body>
  39.     <div class="container">
  40.         <h1>jQuery UI进度条事件示例</h1>
  41.         
  42.         <div id="progressbar"></div>
  43.         
  44.         <div class="controls">
  45.             <button id="start-btn">开始</button>
  46.             <button id="reset-btn">重置</button>
  47.         </div>
  48.         
  49.         <h3>事件日志:</h3>
  50.         <div class="event-log" id="event-log"></div>
  51.     </div>
  52.    
  53.     <script>
  54.         $(document).ready(function() {
  55.             let progressTimer;
  56.             let progressbar = $("#progressbar");
  57.             let eventLog = $("#event-log");
  58.             
  59.             // 添加日志条目
  60.             function addLog(message) {
  61.                 let timestamp = new Date().toLocaleTimeString();
  62.                 eventLog.append("<div class='log-entry'>[" + timestamp + "] " + message + "</div>");
  63.                 // 自动滚动到底部
  64.                 eventLog.scrollTop(eventLog[0].scrollHeight);
  65.             }
  66.             
  67.             // 初始化进度条
  68.             progressbar.progressbar({
  69.                 value: 0,
  70.                 create: function(event, ui) {
  71.                     addLog("进度条已创建");
  72.                 },
  73.                 change: function(event, ui) {
  74.                     let value = $(this).progressbar("value");
  75.                     addLog("进度已更改为: " + value + "%");
  76.                 },
  77.                 complete: function(event, ui) {
  78.                     addLog("进度已完成!");
  79.                     clearInterval(progressTimer);
  80.                     progressTimer = null;
  81.                 }
  82.             });
  83.             
  84.             // 开始按钮点击事件
  85.             $("#start-btn").click(function() {
  86.                 if (!progressTimer) {
  87.                     addLog("开始进度更新");
  88.                     progressTimer = setInterval(function() {
  89.                         let value = progressbar.progressbar("value") || 0;
  90.                         if (value < 100) {
  91.                             progressbar.progressbar("value", value + 1);
  92.                         }
  93.                     }, 100);
  94.                 }
  95.             });
  96.             
  97.             // 重置按钮点击事件
  98.             $("#reset-btn").click(function() {
  99.                 clearInterval(progressTimer);
  100.                 progressTimer = null;
  101.                 progressbar.progressbar("value", 0);
  102.                 addLog("进度已重置");
  103.             });
  104.         });
  105.     </script>
  106. </body>
  107. </html>
复制代码

5. 自定义进度条样式

jQuery UI进度条可以通过CSS进行样式自定义,使其符合网站的整体设计风格。

5.1 基本样式自定义

进度条由几个主要部分组成,可以通过CSS选择器进行自定义:
  1. /* 进度条容器 */
  2. .ui-progressbar {
  3.     height: 20px;
  4.     border: 1px solid #ccc;
  5.     background-color: #f6f6f6;
  6.     border-radius: 4px;
  7. }
  8. /* 进度条值部分 */
  9. .ui-progressbar-value {
  10.     background-color: #3399ff;
  11.     border-radius: 3px;
  12. }
  13. /* 禁用状态的进度条 */
  14. .ui-progressbar-disabled .ui-progressbar-value {
  15.     background-color: #cccccc;
  16. }
复制代码

5.2 高级样式自定义

下面是一个更高级的样式自定义示例,包括渐变背景和动画效果:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>jQuery UI进度条样式自定义示例</title>
  7.     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8.     <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  9.     <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
  10.     <style>
  11.         .container {
  12.             width: 80%;
  13.             margin: 50px auto;
  14.             padding: 20px;
  15.         }
  16.         
  17.         /* 基本进度条样式 */
  18.         .custom-progressbar {
  19.             height: 30px;
  20.             border: 1px solid #ddd;
  21.             background-color: #f9f9f9;
  22.             border-radius: 15px;
  23.             box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
  24.             margin-bottom: 20px;
  25.         }
  26.         
  27.         /* 进度条值部分 - 蓝色渐变 */
  28.         .custom-progressbar .ui-progressbar-value {
  29.             background: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
  30.             border-radius: 15px;
  31.             transition: width 0.3s ease;
  32.         }
  33.         
  34.         /* 绿色进度条 */
  35.         .green-progress .ui-progressbar-value {
  36.             background: linear-gradient(to right, #43e97b 0%, #38f9d7 100%);
  37.         }
  38.         
  39.         /* 橙色进度条 */
  40.         .orange-progress .ui-progressbar-value {
  41.             background: linear-gradient(to right, #fa709a 0%, #fee140 100%);
  42.         }
  43.         
  44.         /* 紫色进度条 */
  45.         .purple-progress .ui-progressbar-value {
  46.             background: linear-gradient(to right, #a18cd1 0%, #fbc2eb 100%);
  47.         }
  48.         
  49.         /* 条纹进度条 */
  50.         .striped-progress .ui-progressbar-value {
  51.             background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
  52.             background-size: 40px 40px;
  53.             background-color: #3399ff;
  54.             animation: progress-bar-stripes 1s linear infinite;
  55.         }
  56.         
  57.         @keyframes progress-bar-stripes {
  58.             0% {
  59.                 background-position: 40px 0;
  60.             }
  61.             100% {
  62.                 background-position: 0 0;
  63.             }
  64.         }
  65.         
  66.         /* 带标签的进度条 */
  67.         .labeled-progress {
  68.             position: relative;
  69.         }
  70.         
  71.         .labeled-progress .progress-label {
  72.             position: absolute;
  73.             top: 0;
  74.             left: 0;
  75.             width: 100%;
  76.             height: 100%;
  77.             text-align: center;
  78.             line-height: 30px;
  79.             color: #333;
  80.             font-weight: bold;
  81.             text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
  82.         }
  83.         
  84.         .controls {
  85.             margin-top: 20px;
  86.         }
  87.         
  88.         button {
  89.             margin-right: 10px;
  90.             padding: 8px 15px;
  91.             background-color: #4facfe;
  92.             color: white;
  93.             border: none;
  94.             border-radius: 4px;
  95.             cursor: pointer;
  96.             transition: background-color 0.3s;
  97.         }
  98.         
  99.         button:hover {
  100.             background-color: #3399ff;
  101.         }
  102.         
  103.         .progress-examples {
  104.             margin-top: 30px;
  105.         }
  106.         
  107.         .progress-example {
  108.             margin-bottom: 20px;
  109.         }
  110.         
  111.         .progress-title {
  112.             margin-bottom: 5px;
  113.             font-weight: bold;
  114.         }
  115.     </style>
  116. </head>
  117. <body>
  118.     <div class="container">
  119.         <h1>jQuery UI进度条样式自定义示例</h1>
  120.         
  121.         <div class="progress-example">
  122.             <div class="progress-title">基本自定义进度条:</div>
  123.             <div id="basic-progress" class="custom-progressbar"></div>
  124.             <div>当前值: <span id="basic-value">0</span>%</div>
  125.         </div>
  126.         
  127.         <div class="progress-example">
  128.             <div class="progress-title">绿色进度条:</div>
  129.             <div id="green-progress" class="custom-progressbar green-progress"></div>
  130.         </div>
  131.         
  132.         <div class="progress-example">
  133.             <div class="progress-title">橙色进度条:</div>
  134.             <div id="orange-progress" class="custom-progressbar orange-progress"></div>
  135.         </div>
  136.         
  137.         <div class="progress-example">
  138.             <div class="progress-title">紫色进度条:</div>
  139.             <div id="purple-progress" class="custom-progressbar purple-progress"></div>
  140.         </div>
  141.         
  142.         <div class="progress-example">
  143.             <div class="progress-title">条纹进度条:</div>
  144.             <div id="striped-progress" class="custom-progressbar striped-progress"></div>
  145.         </div>
  146.         
  147.         <div class="progress-example">
  148.             <div class="progress-title">带标签的进度条:</div>
  149.             <div id="labeled-progress" class="custom-progressbar labeled-progress">
  150.                 <div class="progress-label">0%</div>
  151.             </div>
  152.         </div>
  153.         
  154.         <div class="controls">
  155.             <button id="start-btn">开始演示</button>
  156.             <button id="reset-btn">重置</button>
  157.         </div>
  158.     </div>
  159.    
  160.     <script>
  161.         $(document).ready(function() {
  162.             let progressTimer;
  163.             
  164.             // 初始化所有进度条
  165.             $("#basic-progress").progressbar({
  166.                 value: 0,
  167.                 change: function() {
  168.                     $("#basic-value").text($(this).progressbar("value"));
  169.                 }
  170.             });
  171.             
  172.             $("#green-progress").progressbar({ value: 0 });
  173.             $("#orange-progress").progressbar({ value: 0 });
  174.             $("#purple-progress").progressbar({ value: 0 });
  175.             $("#striped-progress").progressbar({ value: 0 });
  176.             $("#labeled-progress").progressbar({
  177.                 value: 0,
  178.                 change: function() {
  179.                     $(this).find(".progress-label").text($(this).progressbar("value") + "%");
  180.                 }
  181.             });
  182.             
  183.             // 开始按钮点击事件
  184.             $("#start-btn").click(function() {
  185.                 if (!progressTimer) {
  186.                     progressTimer = setInterval(function() {
  187.                         let value = $("#basic-progress").progressbar("value") || 0;
  188.                         if (value < 100) {
  189.                             value += 1;
  190.                             $("#basic-progress").progressbar("value", value);
  191.                             $("#green-progress").progressbar("value", value);
  192.                             $("#orange-progress").progressbar("value", value);
  193.                             $("#purple-progress").progressbar("value", value);
  194.                             $("#striped-progress").progressbar("value", value);
  195.                             $("#labeled-progress").progressbar("value", value);
  196.                         } else {
  197.                             clearInterval(progressTimer);
  198.                             progressTimer = null;
  199.                         }
  200.                     }, 100);
  201.                 }
  202.             });
  203.             
  204.             // 重置按钮点击事件
  205.             $("#reset-btn").click(function() {
  206.                 clearInterval(progressTimer);
  207.                 progressTimer = null;
  208.                 $("#basic-progress").progressbar("value", 0);
  209.                 $("#green-progress").progressbar("value", 0);
  210.                 $("#orange-progress").progressbar("value", 0);
  211.                 $("#purple-progress").progressbar("value", 0);
  212.                 $("#striped-progress").progressbar("value", 0);
  213.                 $("#labeled-progress").progressbar("value", 0);
  214.             });
  215.         });
  216.     </script>
  217. </body>
  218. </html>
复制代码

6. 进度条方法和API

jQuery UI进度条提供了多种方法和API,使开发者能够以编程方式控制进度条的行为。

6.1 常用方法

destroy方法用于完全移除进度条功能,将元素恢复到原始状态。
  1. // 销毁进度条
  2. $("#progressbar").progressbar("destroy");
复制代码

disable方法用于禁用进度条。
  1. // 禁用进度条
  2. $("#progressbar").progressbar("disable");
复制代码

enable方法用于启用已禁用的进度条。
  1. // 启用进度条
  2. $("#progressbar").progressbar("enable");
复制代码

option方法用于获取或设置进度条的选项值。
  1. // 获取选项值
  2. let value = $("#progressbar").progressbar("option", "value");
  3. console.log("当前值: " + value);
  4. // 设置选项值
  5. $("#progressbar").progressbar("option", "value", 50);
  6. // 设置多个选项
  7. $("#progressbar").progressbar("option", {
  8.     value: 75,
  9.     disabled: false
  10. });
复制代码

value方法用于获取或设置进度条的当前值。
  1. // 获取当前值
  2. let currentValue = $("#progressbar").progressbar("value");
  3. console.log("当前值: " + currentValue);
  4. // 设置新值
  5. $("#progressbar").progressbar("value", 50);
复制代码

6.2 方法使用示例

下面是一个综合使用各种方法的示例:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>jQuery UI进度条方法示例</title>
  7.     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8.     <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  9.     <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
  10.     <style>
  11.         .container {
  12.             width: 80%;
  13.             margin: 50px auto;
  14.             padding: 20px;
  15.         }
  16.         .controls {
  17.             margin-top: 20px;
  18.             display: flex;
  19.             flex-wrap: wrap;
  20.             gap: 10px;
  21.         }
  22.         button {
  23.             padding: 8px 15px;
  24.             background-color: #4facfe;
  25.             color: white;
  26.             border: none;
  27.             border-radius: 4px;
  28.             cursor: pointer;
  29.             transition: background-color 0.3s;
  30.         }
  31.         button:hover {
  32.             background-color: #3399ff;
  33.         }
  34.         .status-info {
  35.             margin-top: 20px;
  36.             padding: 10px;
  37.             background-color: #f9f9f9;
  38.             border: 1px solid #ddd;
  39.             border-radius: 4px;
  40.         }
  41.         .status-item {
  42.             margin-bottom: 5px;
  43.         }
  44.         .method-section {
  45.             margin-top: 30px;
  46.         }
  47.         .method-title {
  48.             font-weight: bold;
  49.             margin-bottom: 10px;
  50.         }
  51.         .input-group {
  52.             margin-bottom: 15px;
  53.         }
  54.         .input-group label {
  55.             display: inline-block;
  56.             width: 150px;
  57.         }
  58.         .input-group input {
  59.             padding: 5px;
  60.             border: 1px solid #ddd;
  61.             border-radius: 4px;
  62.         }
  63.     </style>
  64. </head>
  65. <body>
  66.     <div class="container">
  67.         <h1>jQuery UI进度条方法示例</h1>
  68.         
  69.         <div id="progressbar"></div>
  70.         
  71.         <div class="controls">
  72.             <button id="start-btn">开始</button>
  73.             <button id="pause-btn">暂停</button>
  74.             <button id="reset-btn">重置</button>
  75.             <button id="disable-btn">禁用</button>
  76.             <button id="enable-btn">启用</button>
  77.             <button id="destroy-btn">销毁</button>
  78.             <button id="init-btn">初始化</button>
  79.         </div>
  80.         
  81.         <div class="status-info">
  82.             <div class="status-item">当前值: <span id="current-value">0</span>%</div>
  83.             <div class="status-item">最大值: <span id="max-value">100</span></div>
  84.             <div class="status-item">状态: <span id="status">已初始化</span></div>
  85.         </div>
  86.         
  87.         <div class="method-section">
  88.             <div class="method-title">方法测试:</div>
  89.             
  90.             <div class="input-group">
  91.                 <label for="set-value-input">设置进度值:</label>
  92.                 <input type="number" id="set-value-input" min="0" max="100" value="50">
  93.                 <button id="set-value-btn">设置</button>
  94.             </div>
  95.             
  96.             <div class="input-group">
  97.                 <label for="set-max-input">设置最大值:</label>
  98.                 <input type="number" id="set-max-input" min="1" value="100">
  99.                 <button id="set-max-btn">设置</button>
  100.             </div>
  101.             
  102.             <div class="input-group">
  103.                 <label>获取选项值:</label>
  104.                 <button id="get-value-btn">获取值</button>
  105.                 <button id="get-max-btn">获取最大值</button>
  106.                 <button id="get-disabled-btn">获取禁用状态</button>
  107.             </div>
  108.         </div>
  109.     </div>
  110.    
  111.     <script>
  112.         $(document).ready(function() {
  113.             let progressTimer;
  114.             let progressbar = $("#progressbar");
  115.             let isInitialized = true;
  116.             
  117.             // 初始化进度条
  118.             progressbar.progressbar({
  119.                 value: 0,
  120.                 change: function() {
  121.                     updateStatus();
  122.                 },
  123.                 complete: function() {
  124.                     clearInterval(progressTimer);
  125.                     progressTimer = null;
  126.                     $("#status").text("进度完成");
  127.                 }
  128.             });
  129.             
  130.             // 更新状态信息
  131.             function updateStatus() {
  132.                 if (isInitialized) {
  133.                     let value = progressbar.progressbar("value");
  134.                     let max = progressbar.progressbar("option", "max");
  135.                     let disabled = progressbar.progressbar("option", "disabled");
  136.                     
  137.                     $("#current-value").text(value);
  138.                     $("#max-value").text(max);
  139.                     $("#status").text(disabled ? "已禁用" : "已启用");
  140.                 }
  141.             }
  142.             
  143.             // 开始按钮点击事件
  144.             $("#start-btn").click(function() {
  145.                 if (isInitialized && !progressTimer) {
  146.                     progressTimer = setInterval(function() {
  147.                         let value = progressbar.progressbar("value") || 0;
  148.                         let max = progressbar.progressbar("option", "max");
  149.                         
  150.                         if (value < max) {
  151.                             progressbar.progressbar("value", value + 1);
  152.                         } else {
  153.                             clearInterval(progressTimer);
  154.                             progressTimer = null;
  155.                         }
  156.                     }, 100);
  157.                 }
  158.             });
  159.             
  160.             // 暂停按钮点击事件
  161.             $("#pause-btn").click(function() {
  162.                 if (progressTimer) {
  163.                     clearInterval(progressTimer);
  164.                     progressTimer = null;
  165.                     $("#status").text("已暂停");
  166.                 }
  167.             });
  168.             
  169.             // 重置按钮点击事件
  170.             $("#reset-btn").click(function() {
  171.                 if (isInitialized) {
  172.                     clearInterval(progressTimer);
  173.                     progressTimer = null;
  174.                     progressbar.progressbar("value", 0);
  175.                     $("#status").text("已重置");
  176.                 }
  177.             });
  178.             
  179.             // 禁用按钮点击事件
  180.             $("#disable-btn").click(function() {
  181.                 if (isInitialized) {
  182.                     progressbar.progressbar("disable");
  183.                     updateStatus();
  184.                 }
  185.             });
  186.             
  187.             // 启用按钮点击事件
  188.             $("#enable-btn").click(function() {
  189.                 if (isInitialized) {
  190.                     progressbar.progressbar("enable");
  191.                     updateStatus();
  192.                 }
  193.             });
  194.             
  195.             // 销毁按钮点击事件
  196.             $("#destroy-btn").click(function() {
  197.                 if (isInitialized) {
  198.                     progressbar.progressbar("destroy");
  199.                     isInitialized = false;
  200.                     $("#status").text("已销毁");
  201.                     $("#current-value").text("N/A");
  202.                     $("#max-value").text("N/A");
  203.                 }
  204.             });
  205.             
  206.             // 初始化按钮点击事件
  207.             $("#init-btn").click(function() {
  208.                 if (!isInitialized) {
  209.                     progressbar.progressbar({
  210.                         value: 0,
  211.                         change: function() {
  212.                             updateStatus();
  213.                         },
  214.                         complete: function() {
  215.                             clearInterval(progressTimer);
  216.                             progressTimer = null;
  217.                             $("#status").text("进度完成");
  218.                         }
  219.                     });
  220.                     isInitialized = true;
  221.                     updateStatus();
  222.                     $("#status").text("已初始化");
  223.                 }
  224.             });
  225.             
  226.             // 设置值按钮点击事件
  227.             $("#set-value-btn").click(function() {
  228.                 if (isInitialized) {
  229.                     let value = parseInt($("#set-value-input").val());
  230.                     let max = progressbar.progressbar("option", "max");
  231.                     
  232.                     if (value >= 0 && value <= max) {
  233.                         progressbar.progressbar("value", value);
  234.                     } else {
  235.                         alert("值必须在0和" + max + "之间");
  236.                     }
  237.                 }
  238.             });
  239.             
  240.             // 设置最大值按钮点击事件
  241.             $("#set-max-btn").click(function() {
  242.                 if (isInitialized) {
  243.                     let max = parseInt($("#set-max-input").val());
  244.                     
  245.                     if (max > 0) {
  246.                         progressbar.progressbar("option", "max", max);
  247.                         updateStatus();
  248.                     } else {
  249.                         alert("最大值必须大于0");
  250.                     }
  251.                 }
  252.             });
  253.             
  254.             // 获取值按钮点击事件
  255.             $("#get-value-btn").click(function() {
  256.                 if (isInitialized) {
  257.                     let value = progressbar.progressbar("value");
  258.                     alert("当前值: " + value);
  259.                 }
  260.             });
  261.             
  262.             // 获取最大值按钮点击事件
  263.             $("#get-max-btn").click(function() {
  264.                 if (isInitialized) {
  265.                     let max = progressbar.progressbar("option", "max");
  266.                     alert("最大值: " + max);
  267.                 }
  268.             });
  269.             
  270.             // 获取禁用状态按钮点击事件
  271.             $("#get-disabled-btn").click(function() {
  272.                 if (isInitialized) {
  273.                     let disabled = progressbar.progressbar("option", "disabled");
  274.                     alert("禁用状态: " + (disabled ? "是" : "否"));
  275.                 }
  276.             });
  277.             
  278.             // 初始化状态
  279.             updateStatus();
  280.         });
  281.     </script>
  282. </body>
  283. </html>
复制代码

7. 高级应用和技巧

7.1 文件上传进度条

文件上传是进度条的常见应用场景。下面是一个模拟文件上传进度条的示例:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>jQuery UI文件上传进度条示例</title>
  7.     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8.     <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  9.     <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
  10.     <style>
  11.         .container {
  12.             width: 80%;
  13.             margin: 50px auto;
  14.             padding: 20px;
  15.         }
  16.         .upload-area {
  17.             border: 2px dashed #ccc;
  18.             border-radius: 5px;
  19.             padding: 25px;
  20.             text-align: center;
  21.             margin-bottom: 20px;
  22.             background-color: #f9f9f9;
  23.             cursor: pointer;
  24.             transition: all 0.3s;
  25.         }
  26.         .upload-area:hover {
  27.             border-color: #4facfe;
  28.             background-color: #f0f8ff;
  29.         }
  30.         .upload-area.dragover {
  31.             border-color: #4facfe;
  32.             background-color: #e6f2ff;
  33.         }
  34.         #file-input {
  35.             display: none;
  36.         }
  37.         .file-info {
  38.             margin-top: 15px;
  39.             padding: 10px;
  40.             background-color: #f0f0f0;
  41.             border-radius: 4px;
  42.             display: none;
  43.         }
  44.         .progress-container {
  45.             margin-top: 20px;
  46.             display: none;
  47.         }
  48.         .upload-progress {
  49.             margin-bottom: 10px;
  50.         }
  51.         .progress-info {
  52.             display: flex;
  53.             justify-content: space-between;
  54.             margin-top: 5px;
  55.         }
  56.         .upload-status {
  57.             margin-top: 10px;
  58.             font-weight: bold;
  59.         }
  60.         .upload-status.success {
  61.             color: #4caf50;
  62.         }
  63.         .upload-status.error {
  64.             color: #f44336;
  65.         }
  66.         button {
  67.             padding: 8px 15px;
  68.             background-color: #4facfe;
  69.             color: white;
  70.             border: none;
  71.             border-radius: 4px;
  72.             cursor: pointer;
  73.             margin-right: 10px;
  74.             transition: background-color 0.3s;
  75.         }
  76.         button:hover {
  77.             background-color: #3399ff;
  78.         }
  79.         button:disabled {
  80.             background-color: #cccccc;
  81.             cursor: not-allowed;
  82.         }
  83.         .file-list {
  84.             margin-top: 20px;
  85.         }
  86.         .file-item {
  87.             display: flex;
  88.             justify-content: space-between;
  89.             align-items: center;
  90.             padding: 10px;
  91.             border-bottom: 1px solid #eee;
  92.         }
  93.         .file-name {
  94.             flex-grow: 1;
  95.         }
  96.         .file-size {
  97.             margin-right: 15px;
  98.             color: #666;
  99.         }
  100.         .file-status {
  101.             font-weight: bold;
  102.         }
  103.         .file-status.success {
  104.             color: #4caf50;
  105.         }
  106.         .file-status.error {
  107.             color: #f44336;
  108.         }
  109.         .file-status.uploading {
  110.             color: #2196f3;
  111.         }
  112.     </style>
  113. </head>
  114. <body>
  115.     <div class="container">
  116.         <h1>jQuery UI文件上传进度条示例</h1>
  117.         
  118.         <div class="upload-area" id="upload-area">
  119.             <p>点击或拖拽文件到此处上传</p>
  120.             <input type="file" id="file-input" multiple>
  121.         </div>
  122.         
  123.         <div class="file-info" id="file-info">
  124.             <div>已选择 <span id="file-count">0</span> 个文件</div>
  125.             <div>总大小: <span id="total-size">0 KB</span></div>
  126.         </div>
  127.         
  128.         <div class="progress-container" id="progress-container">
  129.             <div class="upload-progress" id="upload-progress"></div>
  130.             <div class="progress-info">
  131.                 <div>上传进度: <span id="progress-percent">0</span>%</div>
  132.                 <div>已上传: <span id="uploaded-size">0 KB</span> / <span id="file-total-size">0 KB</span></div>
  133.             </div>
  134.             <div class="upload-status" id="upload-status"></div>
  135.             <div style="margin-top: 10px;">
  136.                 <button id="start-upload">开始上传</button>
  137.                 <button id="cancel-upload" disabled>取消上传</button>
  138.             </div>
  139.         </div>
  140.         
  141.         <div class="file-list" id="file-list">
  142.             <!-- 上传的文件列表将显示在这里 -->
  143.         </div>
  144.     </div>
  145.    
  146.     <script>
  147.         $(document).ready(function() {
  148.             let uploadArea = $("#upload-area");
  149.             let fileInput = $("#file-input");
  150.             let fileInfo = $("#file-info");
  151.             let fileCount = $("#file-count");
  152.             let totalSize = $("#total-size");
  153.             let progressContainer = $("#progress-container");
  154.             let uploadProgress = $("#upload-progress");
  155.             let progressPercent = $("#progress-percent");
  156.             let uploadedSize = $("#uploaded-size");
  157.             let fileTotalSize = $("#file-total-size");
  158.             let uploadStatus = $("#upload-status");
  159.             let startUploadBtn = $("#start-upload");
  160.             let cancelUploadBtn = $("#cancel-upload");
  161.             let fileList = $("#file-list");
  162.             
  163.             let selectedFiles = [];
  164.             let uploadTimer = null;
  165.             let isUploading = false;
  166.             
  167.             // 初始化进度条
  168.             uploadProgress.progressbar({
  169.                 value: 0,
  170.                 max: 100
  171.             });
  172.             
  173.             // 点击上传区域触发文件选择
  174.             uploadArea.click(function() {
  175.                 fileInput.click();
  176.             });
  177.             
  178.             // 文件选择变化事件
  179.             fileInput.change(function() {
  180.                 handleFiles(this.files);
  181.             });
  182.             
  183.             // 拖拽事件
  184.             uploadArea.on("dragover", function(e) {
  185.                 e.preventDefault();
  186.                 uploadArea.addClass("dragover");
  187.             });
  188.             
  189.             uploadArea.on("dragleave", function() {
  190.                 uploadArea.removeClass("dragover");
  191.             });
  192.             
  193.             uploadArea.on("drop", function(e) {
  194.                 e.preventDefault();
  195.                 uploadArea.removeClass("dragover");
  196.                 handleFiles(e.originalEvent.dataTransfer.files);
  197.             });
  198.             
  199.             // 处理选择的文件
  200.             function handleFiles(files) {
  201.                 if (files.length > 0) {
  202.                     selectedFiles = Array.from(files);
  203.                     
  204.                     // 显示文件信息
  205.                     let totalFileSize = 0;
  206.                     selectedFiles.forEach(function(file) {
  207.                         totalFileSize += file.size;
  208.                     });
  209.                     
  210.                     fileCount.text(selectedFiles.length);
  211.                     totalSize.text(formatFileSize(totalFileSize));
  212.                     fileTotalSize.text(formatFileSize(totalFileSize));
  213.                     fileInfo.show();
  214.                     progressContainer.show();
  215.                     
  216.                     // 重置进度条
  217.                     uploadProgress.progressbar("value", 0);
  218.                     progressPercent.text("0");
  219.                     uploadedSize.text("0 KB");
  220.                     uploadStatus.text("");
  221.                     uploadStatus.removeClass("success error");
  222.                     
  223.                     // 启用开始上传按钮
  224.                     startUploadBtn.prop("disabled", false);
  225.                     cancelUploadBtn.prop("disabled", true);
  226.                     
  227.                     // 显示文件列表
  228.                     displayFileList();
  229.                 }
  230.             }
  231.             
  232.             // 显示文件列表
  233.             function displayFileList() {
  234.                 fileList.empty();
  235.                
  236.                 selectedFiles.forEach(function(file, index) {
  237.                     let fileItem = $("<div class='file-item'></div>");
  238.                     let fileName = $("<div class='file-name'></div>").text(file.name);
  239.                     let fileSize = $("<div class='file-size'></div>").text(formatFileSize(file.size));
  240.                     let fileStatus = $("<div class='file-status'></div>").text("等待上传");
  241.                     
  242.                     fileItem.append(fileName);
  243.                     fileItem.append(fileSize);
  244.                     fileItem.append(fileStatus);
  245.                     
  246.                     fileList.append(fileItem);
  247.                 });
  248.             }
  249.             
  250.             // 开始上传按钮点击事件
  251.             startUploadBtn.click(function() {
  252.                 if (selectedFiles.length > 0 && !isUploading) {
  253.                     isUploading = true;
  254.                     startUploadBtn.prop("disabled", true);
  255.                     cancelUploadBtn.prop("disabled", false);
  256.                     uploadStatus.text("上传中...");
  257.                     uploadStatus.removeClass("success error");
  258.                     
  259.                     // 模拟文件上传进度
  260.                     simulateUpload();
  261.                 }
  262.             });
  263.             
  264.             // 取消上传按钮点击事件
  265.             cancelUploadBtn.click(function() {
  266.                 if (isUploading) {
  267.                     clearInterval(uploadTimer);
  268.                     isUploading = false;
  269.                     startUploadBtn.prop("disabled", false);
  270.                     cancelUploadBtn.prop("disabled", true);
  271.                     uploadStatus.text("上传已取消");
  272.                     uploadStatus.addClass("error");
  273.                     
  274.                     // 更新文件列表状态
  275.                     updateFileListStatus("error");
  276.                 }
  277.             });
  278.             
  279.             // 模拟文件上传进度
  280.             function simulateUpload() {
  281.                 let uploadedBytes = 0;
  282.                 let totalBytes = 0;
  283.                
  284.                 selectedFiles.forEach(function(file) {
  285.                     totalBytes += file.size;
  286.                 });
  287.                
  288.                 // 更新文件列表状态
  289.                 updateFileListStatus("uploading");
  290.                
  291.                 uploadTimer = setInterval(function() {
  292.                     // 每次增加总大小的1%
  293.                     uploadedBytes += totalBytes / 100;
  294.                     
  295.                     if (uploadedBytes >= totalBytes) {
  296.                         uploadedBytes = totalBytes;
  297.                         clearInterval(uploadTimer);
  298.                         
  299.                         // 上传完成
  300.                         uploadProgress.progressbar("value", 100);
  301.                         progressPercent.text("100");
  302.                         uploadedSize.text(formatFileSize(uploadedBytes));
  303.                         uploadStatus.text("上传完成!");
  304.                         uploadStatus.addClass("success");
  305.                         
  306.                         isUploading = false;
  307.                         startUploadBtn.prop("disabled", true);
  308.                         cancelUploadBtn.prop("disabled", true);
  309.                         
  310.                         // 更新文件列表状态
  311.                         updateFileListStatus("success");
  312.                     } else {
  313.                         // 更新进度
  314.                         let percent = Math.round((uploadedBytes / totalBytes) * 100);
  315.                         uploadProgress.progressbar("value", percent);
  316.                         progressPercent.text(percent);
  317.                         uploadedSize.text(formatFileSize(uploadedBytes));
  318.                     }
  319.                 }, 100);
  320.             }
  321.             
  322.             // 更新文件列表状态
  323.             function updateFileListStatus(status) {
  324.                 let statusText = {
  325.                     "uploading": "上传中",
  326.                     "success": "上传成功",
  327.                     "error": "上传失败"
  328.                 };
  329.                
  330.                 fileList.find(".file-status").each(function(index) {
  331.                     $(this).text(statusText[status]);
  332.                     $(this).removeClass("success error uploading").addClass(status);
  333.                 });
  334.             }
  335.             
  336.             // 格式化文件大小
  337.             function formatFileSize(bytes) {
  338.                 if (bytes === 0) return "0 Bytes";
  339.                
  340.                 const k = 1024;
  341.                 const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
  342.                 const i = Math.floor(Math.log(bytes) / Math.log(k));
  343.                
  344.                 return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  345.             }
  346.         });
  347.     </script>
  348. </body>
  349. </html>
复制代码

7.2 多任务进度条

在复杂应用中,可能需要同时跟踪多个任务的进度。下面是一个多任务进度条的示例:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>jQuery UI多任务进度条示例</title>
  7.     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8.     <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  9.     <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
  10.     <style>
  11.         .container {
  12.             width: 80%;
  13.             margin: 50px auto;
  14.             padding: 20px;
  15.         }
  16.         .task-container {
  17.             margin-bottom: 20px;
  18.             padding: 15px;
  19.             border: 1px solid #ddd;
  20.             border-radius: 5px;
  21.             background-color: #f9f9f9;
  22.         }
  23.         .task-header {
  24.             display: flex;
  25.             justify-content: space-between;
  26.             align-items: center;
  27.             margin-bottom: 10px;
  28.         }
  29.         .task-name {
  30.             font-weight: bold;
  31.         }
  32.         .task-status {
  33.             padding: 3px 8px;
  34.             border-radius: 3px;
  35.             font-size: 12px;
  36.             font-weight: bold;
  37.         }
  38.         .task-status.pending {
  39.             background-color: #e6f7ff;
  40.             color: #1890ff;
  41.         }
  42.         .task-status.running {
  43.             background-color: #f6ffed;
  44.             color: #52c41a;
  45.         }
  46.         .task-status.completed {
  47.             background-color: #fff7e6;
  48.             color: #fa8c16;
  49.         }
  50.         .task-progress {
  51.             margin-bottom: 5px;
  52.         }
  53.         .task-info {
  54.             display: flex;
  55.             justify-content: space-between;
  56.             font-size: 12px;
  57.             color: #666;
  58.         }
  59.         .overall-progress {
  60.             margin-top: 30px;
  61.             padding: 15px;
  62.             border: 1px solid #ddd;
  63.             border-radius: 5px;
  64.             background-color: #f0f8ff;
  65.         }
  66.         .overall-title {
  67.             font-weight: bold;
  68.             margin-bottom: 10px;
  69.             text-align: center;
  70.         }
  71.         .controls {
  72.             margin-top: 20px;
  73.             text-align: center;
  74.         }
  75.         button {
  76.             padding: 8px 15px;
  77.             background-color: #4facfe;
  78.             color: white;
  79.             border: none;
  80.             border-radius: 4px;
  81.             cursor: pointer;
  82.             margin-right: 10px;
  83.             transition: background-color 0.3s;
  84.         }
  85.         button:hover {
  86.             background-color: #3399ff;
  87.         }
  88.         button:disabled {
  89.             background-color: #cccccc;
  90.             cursor: not-allowed;
  91.         }
  92.         .task-custom-progress .ui-progressbar-value {
  93.             background: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
  94.         }
  95.         .overall-custom-progress .ui-progressbar-value {
  96.             background: linear-gradient(to right, #fa709a 0%, #fee140 100%);
  97.         }
  98.     </style>
  99. </head>
  100. <body>
  101.     <div class="container">
  102.         <h1>jQuery UI多任务进度条示例</h1>
  103.         
  104.         <div id="tasks-container">
  105.             <!-- 任务进度条将在这里动态添加 -->
  106.         </div>
  107.         
  108.         <div class="overall-progress">
  109.             <div class="overall-title">总体进度</div>
  110.             <div id="overall-progress" class="overall-custom-progress"></div>
  111.             <div class="task-info">
  112.                 <div>总体进度: <span id="overall-percent">0</span>%</div>
  113.                 <div>已完成: <span id="completed-tasks">0</span> / <span id="total-tasks">0</span> 个任务</div>
  114.             </div>
  115.         </div>
  116.         
  117.         <div class="controls">
  118.             <button id="start-all-btn">开始所有任务</button>
  119.             <button id="pause-all-btn">暂停所有任务</button>
  120.             <button id="reset-all-btn">重置所有任务</button>
  121.         </div>
  122.     </div>
  123.    
  124.     <script>
  125.         $(document).ready(function() {
  126.             let tasks = [
  127.                 { id: 1, name: "任务一: 数据预处理", duration: 3000, progress: 0, status: "pending", timer: null },
  128.                 { id: 2, name: "任务二: 特征提取", duration: 5000, progress: 0, status: "pending", timer: null },
  129.                 { id: 3, name: "任务三: 模型训练", duration: 8000, progress: 0, status: "pending", timer: null },
  130.                 { id: 4, name: "任务四: 模型评估", duration: 4000, progress: 0, status: "pending", timer: null },
  131.                 { id: 5, name: "任务五: 结果可视化", duration: 3000, progress: 0, status: "pending", timer: null }
  132.             ];
  133.             
  134.             let tasksContainer = $("#tasks-container");
  135.             let overallProgress = $("#overall-progress");
  136.             let overallPercent = $("#overall-percent");
  137.             let completedTasks = $("#completed-tasks");
  138.             let totalTasks = $("#total-tasks");
  139.             let startAllBtn = $("#start-all-btn");
  140.             let pauseAllBtn = $("#pause-all-btn");
  141.             let resetAllBtn = $("#reset-all-btn");
  142.             
  143.             // 初始化总体进度条
  144.             overallProgress.progressbar({
  145.                 value: 0,
  146.                 max: 100
  147.             });
  148.             
  149.             // 显示总任务数
  150.             totalTasks.text(tasks.length);
  151.             
  152.             // 创建任务进度条
  153.             function createTaskProgressBars() {
  154.                 tasksContainer.empty();
  155.                
  156.                 tasks.forEach(function(task) {
  157.                     let taskContainer = $("<div class='task-container'></div>");
  158.                     let taskHeader = $("<div class='task-header'></div>");
  159.                     let taskName = $("<div class='task-name'></div>").text(task.name);
  160.                     let taskStatus = $("<div class='task-status pending'></div>").text("等待中");
  161.                     
  162.                     taskHeader.append(taskName);
  163.                     taskHeader.append(taskStatus);
  164.                     
  165.                     let taskProgress = $("<div class='task-progress task-custom-progress' id='task-" + task.id + "-progress'></div>");
  166.                     let taskInfo = $("<div class='task-info'></div>");
  167.                     let taskPercent = $("<div></div>").text("进度: 0%");
  168.                     let taskTime = $("<div></div>").text("剩余时间: 计算中...");
  169.                     
  170.                     taskInfo.append(taskPercent);
  171.                     taskInfo.append(taskTime);
  172.                     
  173.                     taskContainer.append(taskHeader);
  174.                     taskContainer.append(taskProgress);
  175.                     taskContainer.append(taskInfo);
  176.                     
  177.                     tasksContainer.append(taskContainer);
  178.                     
  179.                     // 初始化进度条
  180.                     taskProgress.progressbar({
  181.                         value: 0,
  182.                         max: 100
  183.                     });
  184.                 });
  185.             }
  186.             
  187.             // 开始所有任务
  188.             function startAllTasks() {
  189.                 tasks.forEach(function(task) {
  190.                     if (task.status === "pending" || task.status === "paused") {
  191.                         startTask(task);
  192.                     }
  193.                 });
  194.                
  195.                 startAllBtn.prop("disabled", true);
  196.                 pauseAllBtn.prop("disabled", false);
  197.             }
  198.             
  199.             // 开始单个任务
  200.             function startTask(task) {
  201.                 task.status = "running";
  202.                 updateTaskStatus(task);
  203.                
  204.                 let startTime = Date.now();
  205.                 let remainingTime = task.duration * (1 - task.progress / 100);
  206.                
  207.                 task.timer = setInterval(function() {
  208.                     let elapsed = Date.now() - startTime;
  209.                     let progressIncrement = (elapsed / task.duration) * 100;
  210.                     
  211.                     task.progress = Math.min(100, task.progress + progressIncrement);
  212.                     
  213.                     // 更新进度条
  214.                     let taskProgress = $("#task-" + task.id + "-progress");
  215.                     taskProgress.progressbar("value", task.progress);
  216.                     
  217.                     // 更新任务信息
  218.                     let taskContainer = taskProgress.closest(".task-container");
  219.                     taskContainer.find(".task-info div:first").text("进度: " + Math.round(task.progress) + "%");
  220.                     
  221.                     // 计算剩余时间
  222.                     remainingTime = task.duration * (1 - task.progress / 100);
  223.                     if (remainingTime > 0) {
  224.                         taskContainer.find(".task-info div:last").text("剩余时间: " + formatTime(remainingTime));
  225.                     } else {
  226.                         taskContainer.find(".task-info div:last").text("剩余时间: 完成");
  227.                     }
  228.                     
  229.                     // 更新总体进度
  230.                     updateOverallProgress();
  231.                     
  232.                     // 检查任务是否完成
  233.                     if (task.progress >= 100) {
  234.                         clearInterval(task.timer);
  235.                         task.status = "completed";
  236.                         updateTaskStatus(task);
  237.                         
  238.                         // 检查是否所有任务都已完成
  239.                         if (tasks.every(t => t.status === "completed")) {
  240.                             startAllBtn.prop("disabled", false);
  241.                             pauseAllBtn.prop("disabled", true);
  242.                         }
  243.                     }
  244.                     
  245.                     // 重置开始时间
  246.                     startTime = Date.now();
  247.                 }, 100);
  248.             }
  249.             
  250.             // 暂停所有任务
  251.             function pauseAllTasks() {
  252.                 tasks.forEach(function(task) {
  253.                     if (task.status === "running") {
  254.                         clearInterval(task.timer);
  255.                         task.status = "paused";
  256.                         updateTaskStatus(task);
  257.                     }
  258.                 });
  259.                
  260.                 startAllBtn.prop("disabled", false);
  261.                 pauseAllBtn.prop("disabled", true);
  262.             }
  263.             
  264.             // 重置所有任务
  265.             function resetAllTasks() {
  266.                 tasks.forEach(function(task) {
  267.                     if (task.timer) {
  268.                         clearInterval(task.timer);
  269.                     }
  270.                     
  271.                     task.progress = 0;
  272.                     task.status = "pending";
  273.                     
  274.                     // 重置进度条
  275.                     let taskProgress = $("#task-" + task.id + "-progress");
  276.                     taskProgress.progressbar("value", 0);
  277.                     
  278.                     // 重置任务信息
  279.                     let taskContainer = taskProgress.closest(".task-container");
  280.                     taskContainer.find(".task-info div:first").text("进度: 0%");
  281.                     taskContainer.find(".task-info div:last").text("剩余时间: 计算中...");
  282.                     
  283.                     updateTaskStatus(task);
  284.                 });
  285.                
  286.                 // 重置总体进度
  287.                 overallProgress.progressbar("value", 0);
  288.                 overallPercent.text("0");
  289.                 completedTasks.text("0");
  290.                
  291.                 startAllBtn.prop("disabled", false);
  292.                 pauseAllBtn.prop("disabled", true);
  293.             }
  294.             
  295.             // 更新任务状态显示
  296.             function updateTaskStatus(task) {
  297.                 let taskContainer = $("#task-" + task.id + "-progress").closest(".task-container");
  298.                 let statusElement = taskContainer.find(".task-status");
  299.                
  300.                 statusElement.removeClass("pending running completed");
  301.                
  302.                 switch (task.status) {
  303.                     case "pending":
  304.                         statusElement.addClass("pending").text("等待中");
  305.                         break;
  306.                     case "running":
  307.                         statusElement.addClass("running").text("运行中");
  308.                         break;
  309.                     case "paused":
  310.                         statusElement.addClass("pending").text("已暂停");
  311.                         break;
  312.                     case "completed":
  313.                         statusElement.addClass("completed").text("已完成");
  314.                         break;
  315.                 }
  316.             }
  317.             
  318.             // 更新总体进度
  319.             function updateOverallProgress() {
  320.                 let totalProgress = 0;
  321.                 let completedCount = 0;
  322.                
  323.                 tasks.forEach(function(task) {
  324.                     totalProgress += task.progress;
  325.                     if (task.status === "completed") {
  326.                         completedCount++;
  327.                     }
  328.                 });
  329.                
  330.                 let averageProgress = totalProgress / tasks.length;
  331.                 overallProgress.progressbar("value", averageProgress);
  332.                 overallPercent.text(Math.round(averageProgress));
  333.                 completedTasks.text(completedCount);
  334.             }
  335.             
  336.             // 格式化时间
  337.             function formatTime(milliseconds) {
  338.                 let seconds = Math.ceil(milliseconds / 1000);
  339.                 let minutes = Math.floor(seconds / 60);
  340.                 seconds = seconds % 60;
  341.                
  342.                 if (minutes > 0) {
  343.                     return minutes + " 分 " + seconds + " 秒";
  344.                 } else {
  345.                     return seconds + " 秒";
  346.                 }
  347.             }
  348.             
  349.             // 绑定按钮事件
  350.             startAllBtn.click(startAllTasks);
  351.             pauseAllBtn.click(pauseAllTasks);
  352.             resetAllBtn.click(resetAllTasks);
  353.             
  354.             // 初始化任务进度条
  355.             createTaskProgressBars();
  356.         });
  357.     </script>
  358. </body>
  359. </html>
复制代码

7.3 进度条与动画结合

将进度条与动画效果结合可以增强用户体验。下面是一个进度条与动画结合的示例:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>jQuery UI进度条与动画结合示例</title>
  7.     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  8.     <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  9.     <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
  10.     <style>
  11.         .container {
  12.             width: 80%;
  13.             margin: 50px auto;
  14.             padding: 20px;
  15.         }
  16.         .animation-container {
  17.             position: relative;
  18.             height: 300px;
  19.             border: 1px solid #ddd;
  20.             border-radius: 5px;
  21.             overflow: hidden;
  22.             margin-bottom: 20px;
  23.             background-color: #f9f9f9;
  24.         }
  25.         .animated-object {
  26.             position: absolute;
  27.             width: 50px;
  28.             height: 50px;
  29.             background-color: #4facfe;
  30.             border-radius: 50%;
  31.             top: 20px;
  32.             left: 20px;
  33.             display: flex;
  34.             align-items: center;
  35.             justify-content: center;
  36.             color: white;
  37.             font-weight: bold;
  38.             box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  39.         }
  40.         .progress-container {
  41.             margin-top: 20px;
  42.         }
  43.         .animated-progress {
  44.             margin-bottom: 10px;
  45.         }
  46.         .progress-info {
  47.             display: flex;
  48.             justify-content: space-between;
  49.             margin-top: 5px;
  50.         }
  51.         .controls {
  52.             margin-top: 20px;
  53.             text-align: center;
  54.         }
  55.         button {
  56.             padding: 8px 15px;
  57.             background-color: #4facfe;
  58.             color: white;
  59.             border: none;
  60.             border-radius: 4px;
  61.             cursor: pointer;
  62.             margin-right: 10px;
  63.             transition: background-color 0.3s;
  64.         }
  65.         button:hover {
  66.             background-color: #3399ff;
  67.         }
  68.         button:disabled {
  69.             background-color: #cccccc;
  70.             cursor: not-allowed;
  71.         }
  72.         .animation-path {
  73.             position: absolute;
  74.             top: 0;
  75.             left: 0;
  76.             width: 100%;
  77.             height: 100%;
  78.             pointer-events: none;
  79.         }
  80.         .animated-progress .ui-progressbar-value {
  81.             background: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);
  82.             transition: width 0.3s ease;
  83.         }
  84.         .status-message {
  85.             margin-top: 15px;
  86.             padding: 10px;
  87.             border-radius: 4px;
  88.             text-align: center;
  89.             font-weight: bold;
  90.             display: none;
  91.         }
  92.         .status-message.success {
  93.             background-color: #f6ffed;
  94.             color: #52c41a;
  95.             border: 1px solid #b7eb8f;
  96.         }
  97.         .status-message.info {
  98.             background-color: #e6f7ff;
  99.             color: #1890ff;
  100.             border: 1px solid #91d5ff;
  101.         }
  102.     </style>
  103. </head>
  104. <body>
  105.     <div class="container">
  106.         <h1>jQuery UI进度条与动画结合示例</h1>
  107.         
  108.         <div class="animation-container" id="animation-container">
  109.             <svg class="animation-path" id="animation-path">
  110.                 <!-- 动画路径将在这里动态生成 -->
  111.             </svg>
  112.             <div class="animated-object" id="animated-object">0%</div>
  113.         </div>
  114.         
  115.         <div class="progress-container">
  116.             <div id="animated-progress" class="animated-progress"></div>
  117.             <div class="progress-info">
  118.                 <div>动画进度: <span id="progress-percent">0</span>%</div>
  119.                 <div>当前位置: <span id="current-position">起点</span></div>
  120.             </div>
  121.         </div>
  122.         
  123.         <div class="status-message" id="status-message"></div>
  124.         
  125.         <div class="controls">
  126.             <button id="start-animation">开始动画</button>
  127.             <button id="pause-animation" disabled>暂停动画</button>
  128.             <button id="reset-animation">重置动画</button>
  129.             <select id="path-select">
  130.                 <option value="linear">直线路径</option>
  131.                 <option value="circle">圆形路径</option>
  132.                 <option value="zigzag">锯齿路径</option>
  133.                 <option value="spiral">螺旋路径</option>
  134.             </select>
  135.         </div>
  136.     </div>
  137.    
  138.     <script>
  139.         $(document).ready(function() {
  140.             let animationContainer = $("#animation-container");
  141.             let animatedObject = $("#animated-object");
  142.             let animationPath = $("#animation-path");
  143.             let animatedProgress = $("#animated-progress");
  144.             let progressPercent = $("#progress-percent");
  145.             let currentPosition = $("#current-position");
  146.             let statusMessage = $("#status-message");
  147.             let startAnimationBtn = $("#start-animation");
  148.             let pauseAnimationBtn = $("#pause-animation");
  149.             let resetAnimationBtn = $("#reset-animation");
  150.             let pathSelect = $("#path-select");
  151.             
  152.             let animationTimer = null;
  153.             let currentProgress = 0;
  154.             let isAnimating = false;
  155.             let pathType = "linear";
  156.             
  157.             // 初始化进度条
  158.             animatedProgress.progressbar({
  159.                 value: 0,
  160.                 max: 100,
  161.                 change: function() {
  162.                     let value = $(this).progressbar("value");
  163.                     progressPercent.text(value);
  164.                     animatedObject.text(value + "%");
  165.                 },
  166.                 complete: function() {
  167.                     showStatus("动画完成!", "success");
  168.                     isAnimating = false;
  169.                     startAnimationBtn.prop("disabled", false);
  170.                     pauseAnimationBtn.prop("disabled", true);
  171.                 }
  172.             });
  173.             
  174.             // 显示状态消息
  175.             function showStatus(message, type) {
  176.                 statusMessage.text(message);
  177.                 statusMessage.removeClass("success info").addClass(type);
  178.                 statusMessage.fadeIn();
  179.                
  180.                 setTimeout(function() {
  181.                     statusMessage.fadeOut();
  182.                 }, 3000);
  183.             }
  184.             
  185.             // 生成路径
  186.             function generatePath(type) {
  187.                 animationPath.empty();
  188.                 let containerWidth = animationContainer.width();
  189.                 let containerHeight = animationContainer.height();
  190.                 let path = "";
  191.                
  192.                 switch (type) {
  193.                     case "linear":
  194.                         // 直线路径
  195.                         path = `M 20,${containerHeight / 2} L ${containerWidth - 70},${containerHeight / 2}`;
  196.                         currentPosition.text("直线路径");
  197.                         break;
  198.                         
  199.                     case "circle":
  200.                         // 圆形路径
  201.                         let centerX = containerWidth / 2;
  202.                         let centerY = containerHeight / 2;
  203.                         let radius = Math.min(containerWidth, containerHeight) / 2 - 50;
  204.                         path = `M ${centerX + radius},${centerY} A ${radius},${radius} 0 1,1 ${centerX + radius - 0.1},${centerY}`;
  205.                         currentPosition.text("圆形路径");
  206.                         break;
  207.                         
  208.                     case "zigzag":
  209.                         // 锯齿路径
  210.                         let segments = 5;
  211.                         let segmentWidth = (containerWidth - 90) / segments;
  212.                         let amplitude = containerHeight / 3;
  213.                         
  214.                         path = `M 20,${containerHeight / 2}`;
  215.                         for (let i = 1; i <= segments; i++) {
  216.                             let x = 20 + i * segmentWidth;
  217.                             let y = (i % 2 === 0) ? containerHeight / 2 + amplitude : containerHeight / 2 - amplitude;
  218.                             path += ` L ${x},${y}`;
  219.                         }
  220.                         currentPosition.text("锯齿路径");
  221.                         break;
  222.                         
  223.                     case "spiral":
  224.                         // 螺旋路径
  225.                         let spiralCenterX = containerWidth / 2;
  226.                         let spiralCenterY = containerHeight / 2;
  227.                         let spiralRadius = Math.min(containerWidth, containerHeight) / 2 - 50;
  228.                         let turns = 3;
  229.                         
  230.                         path = `M ${spiralCenterX + 10},${spiralCenterY}`;
  231.                         for (let i = 0; i <= 100; i++) {
  232.                             let angle = 0.1 * i * turns;
  233.                             let radius = 10 + (spiralRadius - 10) * (i / 100);
  234.                             let x = spiralCenterX + radius * Math.cos(angle);
  235.                             let y = spiralCenterY + radius * Math.sin(angle);
  236.                             path += ` L ${x},${y}`;
  237.                         }
  238.                         currentPosition.text("螺旋路径");
  239.                         break;
  240.                 }
  241.                
  242.                 // 创建SVG路径元素
  243.                 let pathElement = document.createElementNS("http://www.w3.org/2000/svg", "path");
  244.                 pathElement.setAttribute("d", path);
  245.                 pathElement.setAttribute("fill", "none");
  246.                 pathElement.setAttribute("stroke", "#ddd");
  247.                 pathElement.setAttribute("stroke-width", "2");
  248.                 pathElement.setAttribute("stroke-dasharray", "5,5");
  249.                
  250.                 animationPath.append(pathElement);
  251.                
  252.                 return path;
  253.             }
  254.             
  255.             // 获取路径上的点
  256.             function getPointAtLength(path, length) {
  257.                 let svg = animationPath[0];
  258.                 let pathElement = svg.querySelector("path");
  259.                
  260.                 if (pathElement) {
  261.                     return pathElement.getPointAtLength(length);
  262.                 }
  263.                
  264.                 return { x: 20, y: animationContainer.height() / 2 };
  265.             }
  266.             
  267.             // 开始动画
  268.             function startAnimation() {
  269.                 if (!isAnimating) {
  270.                     isAnimating = true;
  271.                     startAnimationBtn.prop("disabled", true);
  272.                     pauseAnimationBtn.prop("disabled", false);
  273.                     
  274.                     // 生成路径
  275.                     let path = generatePath(pathType);
  276.                     let svg = animationPath[0];
  277.                     let pathElement = svg.querySelector("path");
  278.                     
  279.                     if (pathElement) {
  280.                         let pathLength = pathElement.getTotalLength();
  281.                         
  282.                         animationTimer = setInterval(function() {
  283.                             if (currentProgress < 100) {
  284.                                 currentProgress += 1;
  285.                                 animatedProgress.progressbar("value", currentProgress);
  286.                                 
  287.                                 // 计算对象位置
  288.                                 let length = pathLength * (currentProgress / 100);
  289.                                 let point = getPointAtLength(path, length);
  290.                                 
  291.                                 // 更新对象位置
  292.                                 animatedObject.css({
  293.                                     left: point.x - 25,
  294.                                     top: point.y - 25
  295.                                 });
  296.                             } else {
  297.                                 clearInterval(animationTimer);
  298.                                 animationTimer = null;
  299.                             }
  300.                         }, 50);
  301.                     }
  302.                 }
  303.             }
  304.             
  305.             // 暂停动画
  306.             function pauseAnimation() {
  307.                 if (isAnimating) {
  308.                     clearInterval(animationTimer);
  309.                     animationTimer = null;
  310.                     isAnimating = false;
  311.                     startAnimationBtn.prop("disabled", false);
  312.                     pauseAnimationBtn.prop("disabled", true);
  313.                     showStatus("动画已暂停", "info");
  314.                 }
  315.             }
  316.             
  317.             // 重置动画
  318.             function resetAnimation() {
  319.                 if (animationTimer) {
  320.                     clearInterval(animationTimer);
  321.                     animationTimer = null;
  322.                 }
  323.                
  324.                 currentProgress = 0;
  325.                 isAnimating = false;
  326.                 animatedProgress.progressbar("value", 0);
  327.                
  328.                 // 重置对象位置
  329.                 animatedObject.css({
  330.                     left: 20,
  331.                     top: 20
  332.                 });
  333.                
  334.                 startAnimationBtn.prop("disabled", false);
  335.                 pauseAnimationBtn.prop("disabled", true);
  336.                
  337.                 // 重新生成路径
  338.                 generatePath(pathType);
  339.             }
  340.             
  341.             // 绑定按钮事件
  342.             startAnimationBtn.click(startAnimation);
  343.             pauseAnimationBtn.click(pauseAnimation);
  344.             resetAnimationBtn.click(resetAnimation);
  345.             
  346.             // 路径选择变化事件
  347.             pathSelect.change(function() {
  348.                 pathType = $(this).val();
  349.                 resetAnimation();
  350.             });
  351.             
  352.             // 初始化路径
  353.             generatePath(pathType);
  354.         });
  355.     </script>
  356. </body>
  357. </html>
复制代码

8. 最佳实践和常见问题解决方案

8.1 最佳实践

进度条应该用于需要一定时间的操作,向用户展示操作进度。对于瞬间完成的操作,不需要使用进度条。
  1. // 不好的做法 - 瞬间完成的操作使用进度条
  2. function quickOperation() {
  3.     $("#progressbar").progressbar({ value: 0 });
  4.     // 瞬间完成的操作
  5.     $("#progressbar").progressbar("value", 100);
  6. }
  7. // 好的做法 - 只为耗时操作使用进度条
  8. function longRunningOperation() {
  9.     $("#progressbar").progressbar({ value: 0 });
  10.    
  11.     // 模拟耗时操作
  12.     let progress = 0;
  13.     let timer = setInterval(function() {
  14.         progress += 5;
  15.         $("#progressbar").progressbar("value", progress);
  16.         
  17.         if (progress >= 100) {
  18.             clearInterval(timer);
  19.         }
  20.     }, 200);
  21. }
复制代码

进度条应该提供有意义的反馈,告诉用户当前正在进行的操作以及预计完成时间。
  1. function meaningfulProgress() {
  2.     $("#progressbar").progressbar({ value: 0 });
  3.     $("#status-message").text("正在初始化...");
  4.    
  5.     // 模拟不同阶段的操作
  6.     setTimeout(function() {
  7.         $("#progressbar").progressbar("value", 25);
  8.         $("#status-message").text("正在加载数据...");
  9.     }, 1000);
  10.    
  11.     setTimeout(function() {
  12.         $("#progressbar").progressbar("value", 50);
  13.         $("#status-message").text("正在处理数据...");
  14.     }, 2000);
  15.    
  16.     setTimeout(function() {
  17.         $("#progressbar").progressbar("value", 75);
  18.         $("#status-message").text("正在生成结果...");
  19.     }, 3000);
  20.    
  21.     setTimeout(function() {
  22.         $("#progressbar").progressbar("value", 100);
  23.         $("#status-message").text("操作完成!");
  24.     }, 4000);
  25. }
复制代码

进度条的更新频率应该适中,过于频繁的更新可能会影响性能,过于稀疏的更新则会导致用户体验不佳。
  1. // 不好的做法 - 过于频繁的更新
  2. function badUpdateFrequency() {
  3.     $("#progressbar").progressbar({ value: 0 });
  4.    
  5.     let progress = 0;
  6.     let timer = setInterval(function() {
  7.         progress += 0.1;
  8.         $("#progressbar").progressbar("value", progress);
  9.         
  10.         if (progress >= 100) {
  11.             clearInterval(timer);
  12.         }
  13.     }, 10); // 每10毫秒更新一次,过于频繁
  14. }
  15. // 好的做法 - 适中的更新频率
  16. function goodUpdateFrequency() {
  17.     $("#progressbar").progressbar({ value: 0 });
  18.    
  19.     let progress = 0;
  20.     let timer = setInterval(function() {
  21.         progress += 1;
  22.         $("#progressbar").progressbar("value", progress);
  23.         
  24.         if (progress >= 100) {
  25.             clearInterval(timer);
  26.         }
  27.     }, 100); // 每100毫秒更新一次,适中
  28. }
复制代码

8.2 常见问题解决方案

如果进度条不显示,可能是由于以下原因:

1. 未正确引入jQuery UI库:确保已正确引入jQuery和jQuery UI库。
  1. <!-- jQuery库 -->
  2. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  3. <!-- jQuery UI库 -->
  4. <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
  5. <!-- jQuery UI CSS -->
  6. <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
复制代码

1. 元素未正确初始化:确保在DOM加载完成后初始化进度条。
  1. // 好的做法 - 确保DOM加载完成后初始化
  2. $(document).ready(function() {
  3.     $("#progressbar").progressbar({ value: 37 });
  4. });
  5. // 或者使用简写形式
  6. $(function() {
  7.     $("#progressbar").progressbar({ value: 37 });
  8. });
复制代码

1. CSS样式问题:检查是否有CSS样式影响了进度条的显示。
  1. /* 确保进度条容器有明确的高度 */
  2. #progressbar {
  3.     height: 20px;
  4. }
复制代码

如果进度条的值不更新,可能是由于以下原因:

1. 未正确调用value方法:确保使用正确的方法更新进度条值。
  1. // 正确的更新方法
  2. $("#progressbar").progressbar("value", 50);
  3. // 错误的更新方法
  4. $("#progressbar").progressbar({ value: 50 }); // 这样会重新初始化进度条,而不是更新值
复制代码

1. 变量作用域问题:确保在正确的上下文中访问进度条元素。
  1. // 不好的做法 - 变量作用域问题
  2. function badScope() {
  3.     let timer;
  4.    
  5.     $("#start-btn").click(function() {
  6.         timer = setInterval(function() {
  7.             let value = $("#progressbar").progressbar("value") || 0;
  8.             if (value < 100) {
  9.                 $("#progressbar").progressbar("value", value + 1);
  10.             } else {
  11.                 clearInterval(timer); // timer可能不是同一个变量
  12.             }
  13.         }, 100);
  14.     });
  15.    
  16.     $("#stop-btn").click(function() {
  17.         clearInterval(timer); // timer可能不是同一个变量
  18.     });
  19. }
  20. // 好的做法 - 使用正确的变量作用域
  21. function goodScope() {
  22.     let timer;
  23.    
  24.     $("#start-btn").click(function() {
  25.         if (!timer) {
  26.             timer = setInterval(function() {
  27.                 let value = $("#progressbar").progressbar("value") || 0;
  28.                 if (value < 100) {
  29.                     $("#progressbar").progressbar("value", value + 1);
  30.                 } else {
  31.                     clearInterval(timer);
  32.                     timer = null;
  33.                 }
  34.             }, 100);
  35.         }
  36.     });
  37.    
  38.     $("#stop-btn").click(function() {
  39.         if (timer) {
  40.             clearInterval(timer);
  41.             timer = null;
  42.         }
  43.     });
  44. }
复制代码

如果进度条的样式不正确,可能是由于以下原因:

1. CSS优先级问题:确保自定义样式有足够的优先级。
  1. /* 不好的做法 - 优先级可能不够 */
  2. .ui-progressbar-value {
  3.     background-color: #3399ff;
  4. }
  5. /* 好的做法 - 增加选择器特异性 */
  6. #progressbar .ui-progressbar-value {
  7.     background-color: #3399ff;
  8. }
  9. /* 或者使用!important(不推荐,除非必要) */
  10. .ui-progressbar-value {
  11.     background-color: #3399ff !important;
  12. }
复制代码

1. 主题冲突:确保没有多个jQuery UI主题冲突。
  1. <!-- 确保只引入一个jQuery UI主题 -->
  2. <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/ui-lightness/jquery-ui.css">
  3. <!-- 不要同时引入多个主题 -->
  4. <!-- <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> -->
复制代码

在处理异步操作时,确保进度条与操作状态同步。
  1. // 不好的做法 - 进度条与异步操作不同步
  2. function badAsyncSync() {
  3.     $("#progressbar").progressbar({ value: 0 });
  4.    
  5.     // 模拟异步操作
  6.     setTimeout(function() {
  7.         // 操作完成,但进度条可能还未更新到100%
  8.         console.log("操作完成");
  9.     }, 2000);
  10.    
  11.     // 更新进度条
  12.     let progress = 0;
  13.     let timer = setInterval(function() {
  14.         progress += 10;
  15.         $("#progressbar").progressbar("value", progress);
  16.         
  17.         if (progress >= 100) {
  18.             clearInterval(timer);
  19.         }
  20.     }, 200);
  21. }
  22. // 好的做法 - 进度条与异步操作同步
  23. function goodAsyncSync() {
  24.     $("#progressbar").progressbar({ value: 0 });
  25.    
  26.     // 更新进度条
  27.     let progress = 0;
  28.     let timer = setInterval(function() {
  29.         progress += 10;
  30.         $("#progressbar").progressbar("value", progress);
  31.         
  32.         if (progress >= 100) {
  33.             clearInterval(timer);
  34.             // 进度条完成后执行操作
  35.             operationComplete();
  36.         }
  37.     }, 200);
  38. }
  39. function operationComplete() {
  40.     console.log("操作完成");
  41.     // 执行完成后的操作
  42. }
复制代码

9. 总结

jQuery UI进度条是一个功能强大且易于使用的组件,可以帮助开发者创建直观的进度指示器,提升用户体验。本教程从基础概念到高级应用,全面介绍了jQuery UI进度条的使用方法和技巧。

通过本教程,我们学习了:

1. jQuery UI进度条的基本概念和准备工作
2. 如何创建和更新基本进度条
3. 进度条的配置选项和事件处理
4. 如何自定义进度条的样式
5. 进度条的方法和API
6. 进度条的高级应用,如文件上传进度条、多任务进度条和与动画结合的进度条
7. 使用进度条的最佳实践和常见问题解决方案

在实际开发中,根据具体需求选择合适的进度条实现方式,并遵循最佳实践,可以创建出既美观又实用的进度指示器,为用户提供良好的操作体验。

希望本教程能够帮助你掌握jQuery UI进度条的开发技巧,并在实际项目中灵活应用。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

频道订阅

频道订阅

加入社群

加入社群

联系我们|TG频道|RSS

Powered by Pixtech

© 2025 Pixtech Team.