适合新手的jQuery UI简易入门教程让你轻松创建美观实用的网页界面无需深厚编程基础即可上手提升开发效率
什么是jQuery UI
jQuery UI是一个基于jQuery的开源JavaScript库,专门用于创建交互式的网页界面。它提供了一套丰富的用户界面组件、效果和主题,使开发者能够轻松构建美观且功能强大的网页应用,而无需深厚的编程基础。
jQuery UI的主要优势包括:
- 易用性:简单的API设计,即使是初学者也能快速上手
- 跨浏览器兼容:支持所有主流浏览器,包括Chrome、Firefox、Safari、IE等
- 主题系统:内置多种主题,也支持自定义主题,满足不同设计需求
- 丰富的组件:提供对话框、日期选择器、进度条、滑块等多种常用UI组件
- 可访问性:遵循WAI-ARIA标准,确保残障用户也能正常使用
jQuery UI特别适合以下人群学习:
- 前端开发初学者
- 需要快速构建原型的设计师
- 希望提升网站交互性的后端开发者
- 对网页界面美化感兴趣的自学者
安装和设置jQuery UI
下载jQuery UI
要开始使用jQuery UI,首先需要下载相关文件。有两种主要方式:
直接下载:访问jQuery UI官方网站,点击下载按钮,选择需要的组件和主题,然后下载压缩包。
使用CDN:直接在HTML中引入CDN链接,这是最简单快捷的方式,特别适合初学者。
引入jQuery和jQuery UI
jQuery UI依赖于jQuery,所以在引入jQuery UI之前必须先引入jQuery。以下是使用CDN方式引入的代码示例:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 入门示例</title> <!-- 引入jQuery UI的CSS样式 --> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <!-- 引入jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- 引入jQuery UI --> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> </head> <body> <!-- 页面内容 --> </body> </html>
基本页面结构
一个使用jQuery UI的基本页面结构如下:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 入门示例</title> <!-- 引入jQuery UI的CSS样式 --> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <!-- 自定义样式 --> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } </style> </head> <body> <div class="container"> <h1>jQuery UI 入门示例</h1> <!-- 这里将放置我们的jQuery UI组件 --> </div> <!-- 引入jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- 引入jQuery UI --> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <!-- 自定义JavaScript代码 --> <script> $(document).ready(function() { // 这里将放置我们的jQuery UI初始化代码 }); </script> </body> </html>
jQuery UI基本组件介绍
jQuery UI提供了多种实用的UI组件,下面我们将介绍一些最常用的组件及其基本用法。
对话框(Dialog)
对话框是网页中常用的交互元素,可以用于显示信息、表单或确认操作。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 对话框示例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } #dialog-message { display: none; } </style> </head> <body> <div class="container"> <h1>jQuery UI 对话框示例</h1> <button id="open-dialog">打开对话框</button> <!-- 对话框内容 --> <div id="dialog-message" title="基本信息"> <p> <span class="ui-icon ui-icon-circle-check" style="float:left; margin:12px 12px 20px 0;"></span> 这是一个简单的对话框示例。对话框可以包含文本、表单或其他HTML内容。 </p> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 初始化对话框 $("#dialog-message").dialog({ autoOpen: false, // 页面加载时不自动打开 modal: true, // 创建模态对话框 buttons: { "确定": function() { $(this).dialog("close"); }, "取消": function() { $(this).dialog("close"); } } }); // 点击按钮打开对话框 $("#open-dialog").on("click", function() { $("#dialog-message").dialog("open"); }); }); </script> </body> </html>
日期选择器(Datepicker)
日期选择器是一个方便用户选择日期的组件,常用于表单中。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 日期选择器示例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; } input[type="text"] { padding: 8px; width: 200px; border: 1px solid #ccc; border-radius: 4px; } </style> </head> <body> <div class="container"> <h1>jQuery UI 日期选择器示例</h1> <div class="form-group"> <label for="datepicker">选择日期:</label> <input type="text" id="datepicker"> </div> <div class="form-group"> <label for="date-range">选择日期范围:</label> <input type="text" id="from-date" placeholder="开始日期"> <input type="text" id="to-date" placeholder="结束日期"> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 基本日期选择器 $("#datepicker").datepicker({ dateFormat: "yy-mm-dd", // 设置日期格式 changeMonth: true, // 允许选择月份 changeYear: true, // 允许选择年份 minDate: 0, // 最小日期为今天 maxDate: "+1Y", // 最大日期为今天后一年 showButtonPanel: true, // 显示按钮面板 closeText: "关闭", // 关闭按钮文本 currentText: "今天", // 今天按钮文本 monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"] }); // 日期范围选择器 $("#from-date").datepicker({ dateFormat: "yy-mm-dd", changeMonth: true, changeYear: true, onClose: function(selectedDate) { // 设置结束日期的最小值为开始日期 $("#to-date").datepicker("option", "minDate", selectedDate); } }); $("#to-date").datepicker({ dateFormat: "yy-mm-dd", changeMonth: true, changeYear: true, onClose: function(selectedDate) { // 设置开始日期的最大值为结束日期 $("#from-date").datepicker("option", "maxDate", selectedDate); } }); }); </script> </body> </html>
进度条(Progressbar)
进度条用于显示任务的完成进度,常用于文件上传、数据处理等场景。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 进度条示例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } .progress-container { margin: 20px 0; } #progressbar { height: 25px; } .progress-label { position: absolute; left: 50%; top: 4px; font-weight: bold; text-shadow: 1px 1px 0 #fff; } .controls { margin-top: 20px; } button { padding: 8px 15px; margin-right: 10px; cursor: pointer; } </style> </head> <body> <div class="container"> <h1>jQuery UI 进度条示例</h1> <div class="progress-container"> <div id="progressbar"> <div class="progress-label">0%</div> </div> </div> <div class="controls"> <button id="start-progress">开始进度</button> <button id="reset-progress">重置</button> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { var progressbar = $("#progressbar"); var progressLabel = $(".progress-label"); var progressTimer; // 初始化进度条 progressbar.progressbar({ value: false, change: function() { progressLabel.text(progressbar.progressbar("value") + "%"); }, complete: function() { progressLabel.text("完成!"); clearInterval(progressTimer); } }); // 开始进度 $("#start-progress").on("click", function() { var value = 0; // 重置进度条 progressbar.progressbar("value", 0); progressLabel.text("0%"); // 模拟进度增加 progressTimer = setInterval(function() { value += 1; progressbar.progressbar("value", value); if (value >= 100) { clearInterval(progressTimer); } }, 100); }); // 重置进度条 $("#reset-progress").on("click", function() { clearInterval(progressTimer); progressbar.progressbar("value", 0); progressLabel.text("0%"); }); }); </script> </body> </html>
滑块(Slider)
滑块允许用户通过拖动滑块选择一个数值或范围。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 滑块示例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } .slider-container { margin: 20px 0; } .slider-label { margin-bottom: 10px; font-weight: bold; } .value-display { margin-top: 10px; padding: 10px; background-color: #f5f5f5; border-radius: 4px; } #slider-range { margin: 20px 0; } .slider-values { display: flex; justify-content: space-between; margin-top: 10px; } </style> </head> <body> <div class="container"> <h1>jQuery UI 滑块示例</h1> <div class="slider-container"> <div class="slider-label">单值滑块:</div> <div id="slider-single"></div> <div class="value-display"> 当前值: <span id="single-value">50</span> </div> </div> <div class="slider-container"> <div class="slider-label">范围滑块:</div> <div id="slider-range"></div> <div class="slider-values"> <div>最小值: <span id="range-min">25</span></div> <div>最大值: <span id="range-max">75</span></div> </div> </div> <div class="slider-container"> <div class="slider-label">带刻度的滑块:</div> <div id="slider-ticks"></div> <div class="value-display"> 当前值: <span id="ticks-value">3</span> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 单值滑块 $("#slider-single").slider({ value: 50, min: 0, max: 100, step: 1, slide: function(event, ui) { $("#single-value").text(ui.value); } }); // 范围滑块 $("#slider-range").slider({ range: true, min: 0, max: 100, values: [25, 75], slide: function(event, ui) { $("#range-min").text(ui.values[0]); $("#range-max").text(ui.values[1]); } }); // 带刻度的滑块 $("#slider-ticks").slider({ value: 3, min: 1, max: 5, step: 1, slide: function(event, ui) { $("#ticks-value").text(ui.value); } }); // 为带刻度的滑块添加刻度标记 var sliderTicks = $("#slider-ticks"); var ticksContainer = $("<div></div>").css({ "position": "relative", "height": "20px", "margin-top": "10px" }); for (var i = 1; i <= 5; i++) { var tick = $("<div></div>").css({ "position": "absolute", "left": ((i - 1) * 25) + "%", "width": "1px", "height": "10px", "background-color": "#888" }); var label = $("<div>" + i + "</div>").css({ "position": "absolute", "left": ((i - 1) * 25) + "%", "transform": "translateX(-50%)", "margin-top": "12px", "font-size": "12px" }); ticksContainer.append(tick).append(label); } sliderTicks.after(ticksContainer); }); </script> </body> </html>
标签页(Tabs)
标签页是一种常见的内容组织方式,可以在有限的空间内展示大量内容。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 标签页示例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } .tab-content { padding: 20px; border: 1px solid #ddd; border-top: none; background-color: #fff; } .feature-list { list-style-type: none; padding: 0; } .feature-list li { padding: 8px 0; border-bottom: 1px solid #eee; } .feature-list li:last-child { border-bottom: none; } .feature-list li:before { content: "✓"; color: #28a745; font-weight: bold; margin-right: 10px; } .pricing-table { width: 100%; border-collapse: collapse; } .pricing-table th, .pricing-table td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; } .pricing-table th { background-color: #f8f9fa; } .price { font-weight: bold; color: #007bff; } </style> </head> <body> <div class="container"> <h1>jQuery UI 标签页示例</h1> <div id="tabs"> <ul> <li><a href="#tabs-1">产品介绍</a></li> <li><a href="#tabs-2">功能特点</a></li> <li><a href="#tabs-3">价格方案</a></li> <li><a href="#tabs-4">用户评价</a></li> </ul> <div id="tabs-1" class="tab-content"> <h2>产品介绍</h2> <p>我们的产品是一款创新的解决方案,旨在帮助用户提高工作效率,简化日常任务。通过直观的界面和强大的功能,用户可以轻松完成各种复杂操作。</p> <p>产品采用最新的技术架构,确保稳定性和安全性。无论您是个人用户还是企业客户,都能从中受益。</p> <p>自发布以来,我们的产品已经服务了数百万用户,获得了广泛的好评和认可。</p> </div> <div id="tabs-2" class="tab-content"> <h2>功能特点</h2> <ul class="feature-list"> <li>直观易用的用户界面,无需学习即可上手</li> <li>强大的数据处理能力,支持大规模数据操作</li> <li>灵活的自定义选项,满足不同用户需求</li> <li>多平台支持,可在各种设备上使用</li> <li>实时协作功能,支持团队共同工作</li> <li>高级安全功能,保护您的数据安全</li> <li>定期更新和改进,持续提供新功能</li> </ul> </div> <div id="tabs-3" class="tab-content"> <h2>价格方案</h2> <table class="pricing-table"> <tr> <th>方案</th> <th>功能</th> <th>价格</th> </tr> <tr> <td>基础版</td> <td>包含基本功能,适合个人用户</td> <td class="price">免费</td> </tr> <tr> <td>专业版</td> <td>包含所有基础功能,增加高级功能,适合专业人士</td> <td class="price">¥99/月</td> </tr> <tr> <td>企业版</td> <td>包含所有功能,增加团队协作和管理功能,适合企业用户</td> <td class="price">¥299/月</td> </tr> </table> </div> <div id="tabs-4" class="tab-content"> <h2>用户评价</h2> <blockquote> <p>"这个产品彻底改变了我的工作方式。以前需要几小时完成的任务,现在只需要几分钟。强烈推荐!"</p> <footer>— 张先生,产品经理</footer> </blockquote> <blockquote> <p>"界面设计非常直观,功能强大且易于使用。客户支持团队也非常专业和响应迅速。"</p> <footer>— 李女士,市场总监</footer> </blockquote> <blockquote> <p>"我们团队使用这个产品已经一年多了,它极大地提高了我们的协作效率。物超所值!"</p> <footer>— 王先生,技术主管</footer> </blockquote> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 初始化标签页 $("#tabs").tabs({ active: 0, // 默认激活第一个标签 event: "click", // 点击切换标签 heightStyle: "content", // 高度自适应内容 show: { effect: "fadeIn", duration: 300 }, // 显示动画 hide: { effect: "fadeOut", duration: 300 } // 隐藏动画 }); }); </script> </body> </html>
折叠面板(Accordion)
折叠面板是一种垂直堆叠的内容区域,用户可以展开或折叠每个面板来查看或隐藏内容。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 折叠面板示例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } .accordion-content { padding: 15px; } .faq-item { margin-bottom: 10px; } .faq-question { font-weight: bold; color: #007bff; } .faq-answer { margin-top: 5px; color: #555; } </style> </head> <body> <div class="container"> <h1>jQuery UI 折叠面板示例</h1> <div id="accordion"> <h3>什么是jQuery UI?</h3> <div class="accordion-content"> <p>jQuery UI是一个基于jQuery的开源JavaScript库,专门用于创建交互式的网页界面。它提供了一套丰富的用户界面组件、效果和主题,使开发者能够轻松构建美观且功能强大的网页应用。</p> <p>jQuery UI包含多种常用组件,如对话框、日期选择器、进度条、滑块、标签页、折叠面板等,这些组件都经过精心设计,具有良好的用户体验和跨浏览器兼容性。</p> </div> <h3>jQuery UI的主要特点</h3> <div class="accordion-content"> <ul> <li><strong>易用性</strong>:简单的API设计,即使是初学者也能快速上手</li> <li><strong>跨浏览器兼容</strong>:支持所有主流浏览器,包括Chrome、Firefox、Safari、IE等</li> <li><strong>主题系统</strong>:内置多种主题,也支持自定义主题,满足不同设计需求</li> <li><strong>丰富的组件</strong>:提供多种常用UI组件,满足各种交互需求</li> <li><strong>可访问性</strong>:遵循WAI-ARIA标准,确保残障用户也能正常使用</li> </ul> </div> <h3>常见问题解答</h3> <div class="accordion-content"> <div class="faq-item"> <div class="faq-question">Q: jQuery UI是否需要付费?</div> <div class="faq-answer">A: 不需要。jQuery UI是一个开源项目,采用MIT许可证,可以免费用于个人和商业项目。</div> </div> <div class="faq-item"> <div class="faq-question">Q: jQuery UI与jQuery是什么关系?</div> <div class="faq-answer">A: jQuery UI是建立在jQuery之上的库,它扩展了jQuery的功能,提供了更多的UI组件和交互效果。使用jQuery UI必须先引入jQuery。</div> </div> <div class="faq-item"> <div class="faq-question">Q: 如何自定义jQuery UI的主题?</div> <div class="faq-answer">A: 可以使用jQuery UI提供的ThemeRoller工具在线创建自定义主题,或者手动修改CSS文件来调整样式。</div> </div> </div> <h3>学习资源</h3> <div class="accordion-content"> <p>想要深入学习jQuery UI,可以参考以下资源:</p> <ul> <li><a href="https://jqueryui.com/" target="_blank">jQuery UI官方网站</a> - 提供完整的文档、演示和下载</li> <li><a href="https://api.jqueryui.com/" target="_blank">jQuery UI API文档</a> - 详细的API参考</li> <li><a href="https://jqueryui.com/themeroller/" target="_blank">ThemeRoller</a> - 在线主题定制工具</li> <li><a href="https://forum.jquery.com/using-jquery-ui" target="_blank">jQuery UI论坛</a> - 社区支持和讨论</li> </ul> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 初始化折叠面板 $("#accordion").accordion({ active: 0, // 默认展开第一个面板 collapsible: true, // 允许折叠所有面板 heightStyle: "content", // 高度自适应内容 icons: { // 设置图标 header: "ui-icon-circle-arrow-e", activeHeader: "ui-icon-circle-arrow-s" }, animate: 300 // 动画持续时间 }); }); </script> </body> </html>
自动完成(Autocomplete)
自动完成组件在用户输入时提供匹配的建议,常用于搜索框、表单输入等场景。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 自动完成示例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 8px; font-weight: bold; } input[type="text"] { padding: 10px; width: 100%; max-width: 400px; border: 1px solid #ccc; border-radius: 4px; } .ui-autocomplete { max-height: 200px; overflow-y: auto; overflow-x: hidden; } .result-info { margin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 4px; display: none; } </style> </head> <body> <div class="container"> <h1>jQuery UI 自动完成示例</h1> <div class="form-group"> <label for="tags">编程语言:</label> <input type="text" id="tags" placeholder="输入编程语言名称..."> </div> <div class="form-group"> <label for="cities">城市:</label> <input type="text" id="cities" placeholder="输入城市名称..."> </div> <div class="form-group"> <label for="products">产品搜索:</label> <input type="text" id="products" placeholder="输入产品名称或编号..."> </div> <div id="result-info" class="result-info"> <h3>选择结果:</h3> <p id="selected-item"></p> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 编程语言自动完成 var availableTags = [ "JavaScript", "Python", "Java", "C++", "C#", "PHP", "Ruby", "Swift", "Go", "Rust", "TypeScript", "Kotlin", "Scala", "R", "MATLAB", "Perl", "Objective-C", "Visual Basic", "SQL", "HTML" ]; $("#tags").autocomplete({ source: availableTags, minLength: 1, // 最小输入字符数 delay: 300, // 延迟时间(毫秒) autoFocus: true, // 自动聚焦到第一项 select: function(event, ui) { showResult("编程语言", ui.item.value); } }); // 城市自动完成(带分类) var cities = [ { label: "北京", category: "直辖市" }, { label: "上海", category: "直辖市" }, { label: "天津", category: "直辖市" }, { label: "重庆", category: "直辖市" }, { label: "广州", category: "广东省" }, { label: "深圳", category: "广东省" }, { label: "杭州", category: "浙江省" }, { label: "南京", category: "江苏省" }, { label: "成都", category: "四川省" }, { label: "武汉", category: "湖北省" }, { label: "西安", category: "陕西省" }, { label: "长沙", category: "湖南省" } ]; $.widget("custom.catcomplete", $.ui.autocomplete, { _create: function() { this._super(); this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)"); }, _renderMenu: function(ul, items) { var that = this, currentCategory = ""; $.each(items, function(index, item) { var li; if (item.category !== currentCategory) { ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>"); currentCategory = item.category; } li = that._renderItemData(ul, item); if (item.category) { li.attr("aria-label", item.category + " : " + item.label); } }); } }); $("#cities").catcomplete({ delay: 0, source: cities, select: function(event, ui) { showResult("城市", ui.item.label + " (" + ui.item.category + ")"); } }); // 产品自动完成(远程数据源) $("#products").autocomplete({ source: function(request, response) { // 模拟远程数据源 var products = [ { id: "P001", label: "笔记本电脑", value: "P001 - 笔记本电脑" }, { id: "P002", label: "智能手机", value: "P002 - 智能手机" }, { id: "P003", label: "平板电脑", value: "P003 - 平板电脑" }, { id: "P004", label: "智能手表", value: "P004 - 智能手表" }, { id: "P005", label: "无线耳机", value: "P005 - 无线耳机" }, { id: "P006", label: "数码相机", value: "P006 - 数码相机" }, { id: "P007", label: "游戏主机", value: "P007 - 游戏主机" }, { id: "P008", label: "智能音箱", value: "P008 - 智能音箱" } ]; // 根据输入过滤产品 var term = request.term.toLowerCase(); var filtered = $.grep(products, function(product) { return product.label.toLowerCase().indexOf(term) !== -1 || product.id.toLowerCase().indexOf(term) !== -1; }); response(filtered); }, minLength: 2, select: function(event, ui) { showResult("产品", ui.item.value); } }); // 显示选择结果 function showResult(type, value) { $("#selected-item").text(type + ": " + value); $("#result-info").show(); } }); </script> </body> </html>
按钮(Button)
jQuery UI的按钮组件可以将各种元素(如按钮、链接、复选框等)转换为美观的按钮样式。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 按钮示例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } .button-group { margin: 20px 0; } .button-group h3 { margin-bottom: 15px; } .toolbar { padding: 10px; background-color: #f8f9fa; border-radius: 4px; margin-bottom: 20px; } .button-set { margin: 15px 0; } .button-set label { margin-right: 10px; } #format { margin-top: 10px; } .notification { padding: 15px; margin: 20px 0; background-color: #d4edda; border: 1px solid #c3e6cb; border-radius: 4px; color: #155724; display: none; } </style> </head> <body> <div class="container"> <h1>jQuery UI 按钮示例</h1> <div class="button-group"> <h3>基本按钮</h3> <button id="button1">按钮1</button> <button id="button2">按钮2</button> <button id="button3">按钮3</button> </div> <div class="button-group"> <h3>图标按钮</h3> <button id="icon-button1">新建</button> <button id="icon-button2">保存</button> <button id="icon-button3">删除</button> </div> <div class="button-group"> <h3>工具栏</h3> <div class="toolbar"> <button id="bold">粗体</button> <button id="italic">斜体</button> <button id="underline">下划线</button> <span style="margin: 0 10px;">|</span> <button id="align-left">左对齐</button> <button id="align-center">居中</button> <button id="align-right">右对齐</button> </div> </div> <div class="button-group"> <h3>按钮组</h3> <div id="radio"> <input type="radio" id="radio1" name="radio"><label for="radio1">选项1</label> <input type="radio" id="radio2" name="radio"><label for="radio2">选项2</label> <input type="radio" id="radio3" name="radio"><label for="radio3">选项3</label> </div> <div id="format"> <input type="checkbox" id="check1"><label for="check1">粗体</label> <input type="checkbox" id="check2"><label for="check2">斜体</label> <input type="checkbox" id="check3"><label for="check3">下划线</label> </div> </div> <div class="button-group"> <h3>链接按钮</h3> <a href="#" id="link-button">链接按钮</a> </div> <div id="notification" class="notification"></div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 基本按钮 $("#button1, #button2, #button3").button({ icon: "ui-icon-gear", showLabel: true }); // 为基本按钮添加点击事件 $("#button1").on("click", function() { showNotification("你点击了按钮1"); }); $("#button2").on("click", function() { showNotification("你点击了按钮2"); }); $("#button3").on("click", function() { showNotification("你点击了按钮3"); }); // 图标按钮 $("#icon-button1").button({ icon: "ui-icon-document", showLabel: true }); $("#icon-button2").button({ icon: "ui-icon-disk", showLabel: true }); $("#icon-button3").button({ icon: "ui-icon-trash", showLabel: true }); // 工具栏按钮 $("#bold").button({ icon: "ui-icon-bold", showLabel: false, text: false }); $("#italic").button({ icon: "ui-icon-italic", showLabel: false, text: false }); $("#underline").button({ icon: "ui-icon-underline", showLabel: false, text: false }); $("#align-left").button({ icon: "ui-icon-align-left", showLabel: false, text: false }); $("#align-center").button({ icon: "ui-icon-align-center", showLabel: false, text: false }); $("#align-right").button({ icon: "ui-icon-align-right", showLabel: false, text: false }); // 按钮组 - 单选按钮 $("#radio").buttonset(); // 为单选按钮添加变化事件 $("input[name='radio']").on("change", function() { var selectedValue = $("input[name='radio']:checked").next("label").text(); showNotification("你选择了: " + selectedValue); }); // 按钮组 - 复选框 $("#format").buttonset(); // 为复选框添加变化事件 $("input[type='checkbox']").on("change", function() { var checkedValues = []; $("input[type='checkbox']:checked").each(function() { checkedValues.push($(this).next("label").text()); }); if (checkedValues.length > 0) { showNotification("你选择了格式: " + checkedValues.join(", ")); } else { showNotification("你没有选择任何格式"); } }); // 链接按钮 $("#link-button").button({ icon: "ui-icon-link", showLabel: true }); // 为链接按钮添加点击事件 $("#link-button").on("click", function(e) { e.preventDefault(); showNotification("你点击了链接按钮"); }); // 显示通知 function showNotification(message) { $("#notification").text(message).fadeIn(300); setTimeout(function() { $("#notification").fadeOut(300); }, 3000); } }); </script> </body> </html>
菜单(Menu)
jQuery UI的菜单组件可以创建水平或垂直的菜单,支持子菜单和图标。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery UI 菜单示例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; } .container { max-width: 800px; margin: 0 auto; } .menu-section { margin: 30px 0; } .menu-section h3 { margin-bottom: 15px; } .ui-menu { width: 200px; } .horizontal-menu .ui-menu { width: auto; display: flex; } .horizontal-menu .ui-menu-item { width: auto; } .menu-content { margin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 4px; min-height: 100px; } .notification { padding: 10px; margin-top: 10px; background-color: #d4edda; border: 1px solid #c3e6cb; border-radius: 4px; color: #155724; display: none; } </style> </head> <body> <div class="container"> <h1>jQuery UI 菜单示例</h1> <div class="menu-section"> <h3>垂直菜单</h3> <ul id="vertical-menu"> <li> <div>文件</div> <ul> <li><div>新建</div></li> <li><div>打开</div></li> <li><div>保存</div></li> <li class="ui-state-disabled"><div>保存为</div></li> <li>--- <li><div>退出</div></li> </ul> </li> <li> <div>编辑</div> <ul> <li><div>撤销</div></li> <li><div>重做</div></li> <li>--- <li><div>剪切</div></li> <li><div>复制</div></li> <li><div>粘贴</div></li> </ul> </li> <li> <div>视图</div> <ul> <li><div>工具栏</div></li> <li><div>状态栏</div></li> <li> <div>缩放</div> <ul> <li><div>放大</div></li> <li><div>缩小</div></li> <li><div>重置</div></li> </ul> </li> </ul> </li> <li> <div>帮助</div> <ul> <li><div>内容</div></li> <li><div>索引</div></li> <li>--- <li><div>关于</div></li> </ul> </li> </ul> </div> <div class="menu-section"> <h3>水平菜单</h3> <div class="horizontal-menu"> <ul id="horizontal-menu"> <li><div>首页</div></li> <li> <div>产品</div> <ul> <li><div>电子产品</div></li> <li><div>家居用品</div></li> <li><div>服装配饰</div></li> <li><div>食品饮料</div></li> </ul> </li> <li> <div>服务</div> <ul> <li><div>技术支持</div></li> <li><div>售后服务</div></li> <li><div>定制服务</div></li> </ul> </li> <li><div>关于我们</div></li> <li><div>联系方式</div></li> </ul> </div> </div> <div class="menu-section"> <h3>带图标的菜单</h3> <ul id="icon-menu"> <li> <div><span class="ui-icon ui-icon-home"></span> 首页</div> </li> <li> <div><span class="ui-icon ui-icon-person"></span> 个人中心</div> <ul> <li><div><span class="ui-icon ui-icon-info"></span> 个人信息</div></li> <li><div><span class="ui-icon ui-icon-key"></span> 修改密码</div></li> <li><div><span class="ui-icon ui-icon-gear"></span> 账户设置</div></li> </ul> </li> <li> <div><span class="ui-icon ui-icon-cart"></span> 购物车</div> </li> <li> <div><span class="ui-icon ui-icon-heart"></span> 收藏夹</div> </li> <li> <div><span class="ui-icon ui-icon-mail-closed"></span> 消息中心</div> <ul> <li><div><span class="ui-icon ui-icon-mail-open"></span> 已读消息</div></li> <li><div><span class="ui-icon ui-icon-mail-closed"></span> 未读消息</div></li> <li><div><span class="ui-icon ui-icon-circle-plus"></span> 发送消息</div></li> </ul> </li> <li> <div><span class="ui-icon ui-icon-power"></span> 退出登录</div> </li> </ul> </div> <div class="menu-content"> <h4>菜单选择结果:</h4> <div id="menu-selection">请从上方菜单中选择一个选项</div> <div id="menu-notification" class="notification"></div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 垂直菜单 $("#vertical-menu").menu({ select: function(event, ui) { var itemText = ui.item.text(); updateSelection("垂直菜单", itemText); // 模拟菜单项功能 if (itemText === "退出") { showNotification("退出应用程序"); } else if (itemText === "新建") { showNotification("创建新文件"); } else if (itemText === "保存") { showNotification("保存文件"); } } }); // 水平菜单 $("#horizontal-menu").menu({ position: { my: "left top", at: "left bottom" }, select: function(event, ui) { var itemText = ui.item.text(); updateSelection("水平菜单", itemText); // 模拟菜单项功能 if (itemText === "首页") { showNotification("导航到首页"); } else if (itemText === "关于我们") { showNotification("显示关于我们页面"); } else if (itemText === "联系方式") { showNotification("显示联系方式页面"); } } }); // 带图标的菜单 $("#icon-menu").menu({ select: function(event, ui) { var itemText = ui.item.text().trim(); // 移除可能的空白字符 updateSelection("图标菜单", itemText); // 模拟菜单项功能 if (itemText === "首页") { showNotification("导航到首页"); } else if (itemText === "退出登录") { showNotification("用户退出登录"); } else if (itemText === "个人信息") { showNotification("显示个人信息页面"); } else if (itemText === "购物车") { showNotification("显示购物车"); } } }); // 更新选择结果 function updateSelection(menuType, itemText) { $("#menu-selection").text(menuType + " - " + itemText); } // 显示通知 function showNotification(message) { var notification = $("#menu-notification"); notification.text(message).fadeIn(300); setTimeout(function() { notification.fadeOut(300); }, 3000); } }); </script> </body> </html>
实际案例演示
现在,让我们通过几个实际案例来展示如何使用jQuery UI创建美观实用的网页界面。
创建一个带有日期选择器的表单
在这个案例中,我们将创建一个活动注册表单,其中包含日期选择器和其他jQuery UI组件。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>活动注册表单 - jQuery UI 实例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f8f9fa; } .container { max-width: 800px; margin: 0 auto; background-color: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } h1 { color: #333; margin-bottom: 20px; text-align: center; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 8px; font-weight: bold; color: #555; } input[type="text"], input[type="email"], input[type="tel"], select, textarea { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; } textarea { height: 100px; resize: vertical; } .form-row { display: flex; gap: 20px; } .form-row .form-group { flex: 1; } .checkbox-group { display: flex; flex-wrap: wrap; gap: 15px; margin-top: 10px; } .checkbox-item { display: flex; align-items: center; } .checkbox-item input { margin-right: 5px; } .ui-spinner { width: 100%; } .ui-datepicker { font-size: 14px; } .submit-btn { background-color: #007bff; color: white; border: none; padding: 12px 30px; font-size: 16px; border-radius: 4px; cursor: pointer; display: block; margin: 30px auto 0; } .submit-btn:hover { background-color: #0069d9; } .success-message { display: none; padding: 15px; background-color: #d4edda; border: 1px solid #c3e6cb; border-radius: 4px; color: #155724; margin-top: 20px; text-align: center; } </style> </head> <body> <div class="container"> <h1>技术研讨会注册表单</h1> <form id="registration-form"> <div class="form-row"> <div class="form-group"> <label for="first-name">姓名:</label> <input type="text" id="first-name" name="first-name" required> </div> <div class="form-group"> <label for="last-name">姓氏:</label> <input type="text" id="last-name" name="last-name" required> </div> </div> <div class="form-group"> <label for="email">电子邮箱:</label> <input type="email" id="email" name="email" required> </div> <div class="form-row"> <div class="form-group"> <label for="phone">电话号码:</label> <input type="tel" id="phone" name="phone" required> </div> <div class="form-group"> <label for="company">公司/组织:</label> <input type="text" id="company" name="company"> </div> </div> <div class="form-row"> <div class="form-group"> <label for="event-date">参会日期:</label> <input type="text" id="event-date" name="event-date" required> </div> <div class="form-group"> <label for="attendees">参会人数:</label> <input id="attendees" name="attendees" value="1" min="1" max="10"> </div> </div> <div class="form-group"> <label for="session">感兴趣的主题:</label> <select id="session" name="session"> <option value="">请选择...</option> <option value="frontend">前端开发</option> <option value="backend">后端开发</option> <option value="mobile">移动应用开发</option> <option value="ai">人工智能</option> <option value="cloud">云计算</option> <option value="security">网络安全</option> </select> </div> <div class="form-group"> <label>特殊需求:</label> <div class="checkbox-group"> <div class="checkbox-item"> <input type="checkbox" id="vegetarian" name="special-needs" value="vegetarian"> <label for="vegetarian">素食餐饮</label> </div> <div class="checkbox-item"> <input type="checkbox" id="parking" name="special-needs" value="parking"> <label for="parking">停车位</label> </div> <div class="checkbox-item"> <input type="checkbox" id="accessibility" name="special-needs" value="accessibility"> <label for="accessibility">无障碍设施</label> </div> <div class="checkbox-item"> <input type="checkbox" id="translation" name="special-needs" value="translation"> <label for="translation">翻译服务</label> </div> </div> </div> <div class="form-group"> <label for="comments">备注:</label> <textarea id="comments" name="comments" placeholder="请输入任何其他信息或特殊要求..."></textarea> </div> <button type="submit" class="submit-btn">提交注册</button> </form> <div id="success-message" class="success-message"> 注册成功!我们将在24小时内通过电子邮件确认您的注册信息。 </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 日期选择器 $("#event-date").datepicker({ dateFormat: "yy-mm-dd", minDate: 0, // 只能选择今天及以后的日期 maxDate: "+3M", // 最多选择3个月后的日期 dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"], monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], showButtonPanel: true, closeText: "关闭", currentText: "今天" }); // 数字微调器 $("#attendees").spinner({ min: 1, max: 10, step: 1 }); // 美化复选框 $("input[type='checkbox']").checkboxradio({ icon: false }); // 表单提交处理 $("#registration-form").on("submit", function(e) { e.preventDefault(); // 简单的表单验证 var isValid = true; var requiredFields = ["#first-name", "#last-name", "#email", "#phone", "#event-date"]; requiredFields.forEach(function(field) { if ($(field).val() === "") { $(field).css("border-color", "red"); isValid = false; } else { $(field).css("border-color", "#ddd"); } }); if (isValid) { // 模拟表单提交 $("#success-message").slideDown(); // 重置表单 setTimeout(function() { $("#registration-form")[0].reset(); $("#success-message").slideUp(); }, 5000); } else { alert("请填写所有必填字段"); } }); }); </script> </body> </html>
构建一个标签页式的内容展示区
这个案例将展示如何使用jQuery UI的标签页组件创建一个产品展示页面。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>产品展示 - jQuery UI 实例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f8f9fa; } .container { max-width: 1200px; margin: 0 auto; background-color: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } h1 { color: #333; margin-bottom: 30px; text-align: center; } .product-header { display: flex; margin-bottom: 30px; } .product-image { flex: 0 0 400px; margin-right: 30px; } .product-image img { width: 100%; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); } .product-info { flex: 1; } .product-title { font-size: 28px; color: #333; margin-bottom: 15px; } .product-price { font-size: 24px; color: #e74c3c; font-weight: bold; margin-bottom: 20px; } .product-description { color: #666; line-height: 1.6; margin-bottom: 25px; } .product-actions { display: flex; gap: 15px; } .btn { padding: 12px 25px; border: none; border-radius: 4px; font-size: 16px; cursor: pointer; transition: background-color 0.3s; } .btn-primary { background-color: #3498db; color: white; } .btn-primary:hover { background-color: #2980b9; } .btn-secondary { background-color: #ecf0f1; color: #333; } .btn-secondary:hover { background-color: #bdc3c7; } .tabs-container { margin-top: 40px; } .tab-content { padding: 25px; border: 1px solid #ddd; border-top: none; background-color: #fff; } .feature-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; } .feature-item { display: flex; align-items: flex-start; } .feature-icon { margin-right: 15px; color: #3498db; font-size: 24px; } .feature-text h4 { margin: 0 0 5px 0; color: #333; } .feature-text p { margin: 0; color: #666; font-size: 14px; } .spec-table { width: 100%; border-collapse: collapse; } .spec-table th, .spec-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; } .spec-table th { background-color: #f8f9fa; font-weight: bold; color: #333; width: 30%; } .review-item { margin-bottom: 25px; padding-bottom: 25px; border-bottom: 1px solid #eee; } .review-item:last-child { border-bottom: none; } .review-header { display: flex; justify-content: space-between; margin-bottom: 10px; } .reviewer-name { font-weight: bold; color: #333; } .review-date { color: #999; font-size: 14px; } .review-rating { color: #f39c12; margin-bottom: 10px; } .review-text { color: #666; line-height: 1.6; } .gallery-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; } .gallery-item img { width: 100%; border-radius: 4px; cursor: pointer; transition: transform 0.3s; } .gallery-item img:hover { transform: scale(1.05); } .notification { position: fixed; top: 20px; right: 20px; padding: 15px 25px; background-color: #2ecc71; color: white; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); display: none; z-index: 1000; } </style> </head> <body> <div class="container"> <h1>智能手机产品展示</h1> <div class="product-header"> <div class="product-image"> <img src="https://picsum.photos/seed/smartphone/400/400.jpg" alt="智能手机产品图"> </div> <div class="product-info"> <h2 class="product-title">UltraPhone Pro Max</h2> <div class="product-price">¥5,999</div> <p class="product-description"> UltraPhone Pro Max 是我们最新推出的旗舰智能手机,配备强大的处理器、高清摄像头和长续航电池。 采用最新的AI技术,为您带来前所未有的智能体验。无论是日常使用还是专业摄影,都能满足您的需求。 </p> <div class="product-actions"> <button class="btn btn-primary" id="add-to-cart">加入购物车</button> <button class="btn btn-secondary" id="add-to-wishlist">收藏</button> </div> </div> </div> <div class="tabs-container"> <div id="product-tabs"> <ul> <li><a href="#tab-features">产品特点</a></li> <li><a href="#tab-specifications">技术规格</a></li> <li><a href="#tab-reviews">用户评价</a></li> <li><a href="#tab-gallery">产品图库</a></li> </ul> <div id="tab-features" class="tab-content"> <h3>产品特点</h3> <div class="feature-grid"> <div class="feature-item"> <div class="feature-icon">📱</div> <div class="feature-text"> <h4>6.7英寸全面屏</h4> <p>超高清AMOLED显示屏,120Hz刷新率,带来流畅的视觉体验</p> </div> </div> <div class="feature-item"> <div class="feature-icon">📷</div> <div class="feature-text"> <h4>四摄像头系统</h4> <p>5000万像素主摄,支持8K视频录制和专业级摄影功能</p> </div> </div> <div class="feature-item"> <div class="feature-icon">🔋</div> <div class="feature-text"> <h4>5000mAh大电池</h4> <p>超长续航,支持65W快充和15W无线充电</p> </div> </div> <div class="feature-item"> <div class="feature-icon">⚡</div> <div class="feature-text"> <h4>旗舰级处理器</h4> <p>最新8核芯片,AI性能提升300%,游戏体验更流畅</p> </div> </div> <div class="feature-item"> <div class="feature-icon">🔒</div> <div class="feature-text"> <h4>安全解锁</h4> <p>屏下指纹识别和3D面部识别双重安全保障</p> </div> </div> <div class="feature-item"> <div class="feature-icon">💧</div> <div class="feature-text"> <h4>IP68防水</h4> <p>全面防水防尘,无惧各种使用环境</p> </div> </div> </div> </div> <div id="tab-specifications" class="tab-content"> <h3>技术规格</h3> <table class="spec-table"> <tr> <th>尺寸与重量</th> <td>160.8 x 78.1 x 7.4 mm,189g</td> </tr> <tr> <th>显示屏</th> <td>6.7英寸AMOLED,分辨率3200 x 1440,120Hz刷新率</td> </tr> <tr> <th>处理器</th> <td>UltraChip A15,8核,主频3.2GHz</td> </tr> <tr> <th>内存</th> <td>12GB RAM,256GB/512GB存储空间</td> </tr> <tr> <th>后置摄像头</th> <td>5000万像素主摄 + 1200万像素超广角 + 800万像素长焦 + 500万像素微距</td> </tr> <tr> <th>前置摄像头</th> <td>3200万像素,支持自动对焦和人像模式</td> </tr> <tr> <th>电池</th> <td>5000mAh,支持65W有线快充和15W无线充电</td> </tr> <tr> <th>操作系统</th> <td>UltraOS 5.0(基于Android 13)</td> </tr> <tr> <th>连接性</th> <td>5G,Wi-Fi 6,蓝牙5.2,NFC,USB Type-C</td> </tr> <tr> <th>安全</th> <td>屏下指纹识别,3D面部识别,AI安全防护</td> </tr> </table> </div> <div id="tab-reviews" class="tab-content"> <h3>用户评价</h3> <div class="review-item"> <div class="review-header"> <div class="reviewer-name">张先生</div> <div class="review-date">2023-10-15</div> </div> <div class="review-rating">★★★★★</div> <div class="review-text"> 这款手机真的超出了我的期望!屏幕显示效果非常出色,色彩鲜艳且细节丰富。 摄像头系统也非常强大,拍出的照片清晰度很高,特别是在低光环境下表现依然出色。 电池续航也很给力,正常使用一天完全没问题。强烈推荐! </div> </div> <div class="review-item"> <div class="review-header"> <div class="reviewer-name">李女士</div> <div class="review-date">2023-10-10</div> </div> <div class="review-rating">★★★★☆</div> <div class="review-text"> 总体来说是一款很不错的手机,性能强劲,系统流畅。特别喜欢它的全面屏设计, 看视频的体验非常好。唯一的小缺点是有点重,长时间拿在手里会有点累。 不过考虑到它的配置和功能,这点重量还是可以接受的。 </div> </div> <div class="review-item"> <div class="review-header"> <div class="reviewer-name">王先生</div> <div class="review-date">2023-10-05</div> </div> <div class="review-rating">★★★★★</div> <div class="review-text"> 作为一个摄影爱好者,我对这款手机的摄像头系统非常满意。 无论是日常拍摄还是专业模式,都能拍出高质量的照片。 特别是长焦镜头,远距离拍摄效果惊人。电池续航也很出色, 即使是长时间使用相机和GPS,也能坚持一整天。 </div> </div> </div> <div id="tab-gallery" class="tab-content"> <h3>产品图库</h3> <div class="gallery-grid"> <div class="gallery-item"> <img src="https://picsum.photos/seed/phone1/300/300.jpg" alt="产品图片1"> </div> <div class="gallery-item"> <img src="https://picsum.photos/seed/phone2/300/300.jpg" alt="产品图片2"> </div> <div class="gallery-item"> <img src="https://picsum.photos/seed/phone3/300/300.jpg" alt="产品图片3"> </div> <div class="gallery-item"> <img src="https://picsum.photos/seed/phone4/300/300.jpg" alt="产品图片4"> </div> <div class="gallery-item"> <img src="https://picsum.photos/seed/phone5/300/300.jpg" alt="产品图片5"> </div> <div class="gallery-item"> <img src="https://picsum.photos/seed/phone6/300/300.jpg" alt="产品图片6"> </div> </div> </div> </div> </div> </div> <div id="notification" class="notification"></div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 初始化标签页 $("#product-tabs").tabs({ active: 0, event: "click", heightStyle: "content", show: { effect: "fadeIn", duration: 300 }, hide: { effect: "fadeOut", duration: 300 } }); // 加入购物车按钮 $("#add-to-cart").on("click", function() { showNotification("产品已成功加入购物车!"); }); // 收藏按钮 $("#add-to-wishlist").on("click", function() { showNotification("产品已添加到收藏夹!"); }); // 产品图片点击放大 $(".gallery-item img").on("click", function() { var imgSrc = $(this).attr("src"); // 创建对话框显示大图 $("<div><img src='" + imgSrc + "' style='width: 100%; height: auto;'></div>").dialog({ modal: true, width: "80%", maxWidth: 800, title: "产品图片", close: function() { $(this).remove(); } }); }); // 显示通知 function showNotification(message) { var notification = $("#notification"); notification.text(message).fadeIn(300); setTimeout(function() { notification.fadeOut(300); }, 3000); } }); </script> </body> </html>
设计一个带有进度条的任务管理界面
这个案例将展示如何使用jQuery UI的进度条、对话框和按钮组件创建一个任务管理界面。
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>任务管理系统 - jQuery UI 实例</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f8f9fa; } .container { max-width: 1000px; margin: 0 auto; background-color: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } h1 { color: #333; margin-bottom: 30px; text-align: center; } .task-controls { display: flex; justify-content: space-between; margin-bottom: 25px; } .task-stats { display: flex; gap: 20px; } .stat-card { background-color: #f8f9fa; border-radius: 6px; padding: 15px; min-width: 120px; text-align: center; } .stat-value { font-size: 24px; font-weight: bold; color: #333; } .stat-label { font-size: 14px; color: #666; margin-top: 5px; } .btn { padding: 10px 20px; border: none; border-radius: 4px; font-size: 14px; cursor: pointer; transition: background-color 0.3s; } .btn-primary { background-color: #3498db; color: white; } .btn-primary:hover { background-color: #2980b9; } .task-list { margin-top: 20px; } .task-item { background-color: #fff; border: 1px solid #eee; border-radius: 6px; padding: 20px; margin-bottom: 15px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); } .task-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; } .task-title { font-size: 18px; font-weight: bold; color: #333; } .task-actions { display: flex; gap: 10px; } .task-description { color: #666; margin-bottom: 15px; line-height: 1.5; } .task-meta { display: flex; justify-content: space-between; font-size: 14px; color: #777; margin-bottom: 15px; } .task-progress { margin-bottom: 10px; } .progress-label { display: flex; justify-content: space-between; margin-bottom: 5px; font-size: 14px; } .progress-value { font-weight: bold; } #task-progressbar { height: 20px; } .progress-label { position: absolute; left: 50%; top: 4px; font-weight: bold; text-shadow: 1px 1px 0 #fff; transform: translateX(-50%); } .priority-high { border-left: 4px solid #e74c3c; } .priority-medium { border-left: 4px solid #f39c12; } .priority-low { border-left: 4px solid #2ecc71; } .task-form { margin-bottom: 20px; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; font-weight: bold; color: #555; } input[type="text"], textarea, select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; } textarea { height: 80px; resize: vertical; } .form-row { display: flex; gap: 15px; } .form-row .form-group { flex: 1; } .notification { position: fixed; top: 20px; right: 20px; padding: 15px 25px; background-color: #2ecc71; color: white; border-radius: 4px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); display: none; z-index: 1000; } .empty-state { text-align: center; padding: 40px 20px; color: #999; } .empty-state-icon { font-size: 48px; margin-bottom: 15px; } </style> </head> <body> <div class="container"> <h1>任务管理系统</h1> <div class="task-controls"> <div class="task-stats"> <div class="stat-card"> <div class="stat-value" id="total-tasks">0</div> <div class="stat-label">总任务</div> </div> <div class="stat-card"> <div class="stat-value" id="completed-tasks">0</div> <div class="stat-label">已完成</div> </div> <div class="stat-card"> <div class="stat-value" id="in-progress-tasks">0</div> <div class="stat-label">进行中</div> </div> </div> <button class="btn btn-primary" id="add-task-btn">添加新任务</button> </div> <div class="task-list" id="task-list"> <div class="empty-state"> <div class="empty-state-icon">📋</div> <p>暂无任务,点击"添加新任务"按钮创建您的第一个任务</p> </div> </div> </div> <!-- 添加/编辑任务对话框 --> <div id="task-dialog" title="添加新任务" style="display: none;"> <form id="task-form"> <div class="form-group"> <label for="task-title">任务标题:</label> <input type="text" id="task-title" name="task-title" required> </div> <div class="form-group"> <label for="task-description">任务描述:</label> <textarea id="task-description" name="task-description"></textarea> </div> <div class="form-row"> <div class="form-group"> <label for="task-priority">优先级:</label> <select id="task-priority" name="task-priority"> <option value="low">低</option> <option value="medium" selected>中</option> <option value="high">高</option> </select> </div> <div class="form-group"> <label for="task-progress">进度 (%):</label> <input type="text" id="task-progress-input" name="task-progress" value="0"> </div> </div> <div class="form-row"> <div class="form-group"> <label for="task-due-date">截止日期:</label> <input type="text" id="task-due-date" name="task-due-date"> </div> <div class="form-group"> <label for="task-category">分类:</label> <select id="task-category" name="task-category"> <option value="work">工作</option> <option value="personal">个人</option> <option value="study">学习</option> <option value="other">其他</option> </select> </div> </div> </form> </div> <div id="notification" class="notification"></div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script> <script> $(document).ready(function() { // 任务数据存储 var tasks = []; var currentTaskId = null; // 初始化日期选择器 $("#task-due-date").datepicker({ dateFormat: "yy-mm-dd", minDate: 0, dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"], monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"] }); // 初始化进度输入框为滑块 $("#task-progress-input").spinner({ min: 0, max: 100, step: 5 }); // 初始化对话框 $("#task-dialog").dialog({ autoOpen: false, modal: true, width: 600, buttons: { "保存": function() { saveTask(); }, "取消": function() { $(this).dialog("close"); } }, close: function() { // 重置表单 $("#task-form")[0].reset(); currentTaskId = null; } }); // 添加任务按钮点击事件 $("#add-task-btn").on("click", function() { $("#task-dialog").dialog("open"); $("#task-dialog").dialog("option", "title", "添加新任务"); }); // 保存任务 function saveTask() { var title = $("#task-title").val().trim(); var description = $("#task-description").val().trim(); var priority = $("#task-priority").val(); var progress = parseInt($("#task-progress-input").val()); var dueDate = $("#task-due-date").val(); var category = $("#task-category").val(); if (!title) { alert("请输入任务标题"); return; } var task = { id: currentTaskId || Date.now(), title: title, description: description, priority: priority, progress: progress, dueDate: dueDate, category: category, createdAt: currentTaskId ? tasks.find(t => t.id === currentTaskId).createdAt : new Date().toISOString() }; if (currentTaskId) { // 更新现有任务 var index = tasks.findIndex(t => t.id === currentTaskId); tasks[index] = task; showNotification("任务已更新"); } else { // 添加新任务 tasks.push(task); showNotification("任务已添加"); } renderTasks(); updateStats(); $("#task-dialog").dialog("close"); } // 渲染任务列表 function renderTasks() { var taskList = $("#task-list"); if (tasks.length === 0) { taskList.html(` <div class="empty-state"> <div class="empty-state-icon">📋</div> <p>暂无任务,点击"添加新任务"按钮创建您的第一个任务</p> </div> `); return; } taskList.empty(); tasks.forEach(function(task) { var priorityClass = "priority-" + task.priority; var priorityText = task.priority === "high" ? "高" : task.priority === "medium" ? "中" : "低"; var categoryText = task.category === "work" ? "工作" : task.category === "personal" ? "个人" : task.category === "study" ? "学习" : "其他"; var taskItem = $(` <div class="task-item ${priorityClass}" data-id="${task.id}"> <div class="task-header"> <div class="task-title">${task.title}</div> <div class="task-actions"> <button class="btn btn-primary edit-task">编辑</button> <button class="btn btn-primary delete-task">删除</button> </div> </div> <div class="task-description">${task.description || "无描述"}</div> <div class="task-meta"> <div>优先级: <span class="priority-${task.priority}">${priorityText}</span></div> <div>分类: ${categoryText}</div> <div>截止日期: ${task.dueDate || "无"}</div> </div> <div class="task-progress"> <div class="progress-label"> <span>进度</span> <span class="progress-value">${task.progress}%</span> </div> <div class="task-progressbar" data-progress="${task.progress}"></div> </div> </div> `); taskList.append(taskItem); // 初始化进度条 taskItem.find(".task-progressbar").progressbar({ value: task.progress }); // 编辑任务按钮点击事件 taskItem.find(".edit-task").on("click", function() { editTask(task.id); }); // 删除任务按钮点击事件 taskItem.find(".delete-task").on("click", function() { deleteTask(task.id); }); }); } // 编辑任务 function editTask(taskId) { var task = tasks.find(t => t.id === taskId); if (!task) return; currentTaskId = taskId; // 填充表单 $("#task-title").val(task.title); $("#task-description").val(task.description); $("#task-priority").val(task.priority); $("#task-progress-input").val(task.progress); $("#task-due-date").val(task.dueDate); $("#task-category").val(task.category); // 打开对话框 $("#task-dialog").dialog("open"); $("#task-dialog").dialog("option", "title", "编辑任务"); } // 删除任务 function deleteTask(taskId) { if (confirm("确定要删除这个任务吗?")) { tasks = tasks.filter(t => t.id !== taskId); renderTasks(); updateStats(); showNotification("任务已删除"); } } // 更新统计数据 function updateStats() { var totalTasks = tasks.length; var completedTasks = tasks.filter(t => t.progress === 100).length; var inProgressTasks = totalTasks - completedTasks; $("#total-tasks").text(totalTasks); $("#completed-tasks").text(completedTasks); $("#in-progress-tasks").text(inProgressTasks); } // 显示通知 function showNotification(message) { var notification = $("#notification"); notification.text(message).fadeIn(300); setTimeout(function() { notification.fadeOut(300); }, 3000); } // 初始化 updateStats(); }); </script> </body> </html>
常见问题和解决方案
在使用jQuery UI的过程中,你可能会遇到一些常见问题。下面是一些常见问题及其解决方案:
兼容性问题
问题:jQuery UI在某些浏览器中显示不正常或功能不工作。
解决方案:
- 确保使用兼容的jQuery版本:jQuery UI需要特定版本的jQuery支持。在jQuery UI官方文档中查看所需的jQuery版本,并确保使用兼容版本。
<!-- 例如,jQuery UI 1.13.2 需要 jQuery 1.7+ --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
- 使用DOCTYPE声明:确保HTML文档开头有正确的DOCTYPE声明,这有助于浏览器以标准模式渲染页面。
<!DOCTYPE html> <html lang="zh-CN"> <head> <!-- 头部内容 --> </head> <body> <!-- 页面内容 --> </body> </html>
- 检查浏览器兼容性:jQuery UI支持大多数现代浏览器,但在旧版浏览器中可能存在兼容性问题。如果需要支持旧版浏览器,可以考虑使用polyfill或降级方案。
样式自定义
问题:默认的jQuery UI主题不符合网站的设计风格。
解决方案:
使用ThemeRoller:jQuery UI提供了ThemeRoller工具,可以在线创建自定义主题。
- 访问jQuery UI ThemeRoller
- 调整颜色、字体和圆角等参数
- 下载自定义主题CSS文件并在项目中引用
<!-- 引入自定义主题 --> <link rel="stylesheet" href="path/to/your/custom-theme/jquery-ui.css">
- 手动覆盖样式:可以通过CSS覆盖jQuery UI的默认样式。
/* 自定义对话框样式 */ .ui-dialog { background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); } .ui-dialog-titlebar { background-color: #007bff; color: white; border-radius: 8px 8px 0 0; } .ui-button { background-color: #007bff; color: white; border: none; border-radius: 4px; } .ui-button:hover { background-color: #0069d9; }
- 使用变量和Sass:如果使用Sass等预处理器,可以通过修改变量来自定义主题。
// 修改jQuery UI的Sass变量 $ui-font-family: 'Arial', sans-serif; $ui-background-color: #f8f9fa; $ui-border-radius: 8px; // 导入jQuery UI的Sass文件 @import "jquery-ui";
性能优化
问题:页面加载缓慢或jQuery UI组件响应迟钝。
解决方案:
- 按需加载组件:不要加载整个jQuery UI库,只加载需要的组件。
<!-- 只加载需要的组件 --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/core.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/datepicker.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/dialog.min.js"></script>
- 使用CDN:使用内容分发网络(CDN)加载jQuery UI,可以提高加载速度。
<!-- 使用CDN加载jQuery UI --> <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
- 延迟初始化:对于非关键组件,可以延迟初始化,直到用户需要时再加载。
// 延迟初始化对话框 $("#open-dialog").on("click", function() { // 动态加载jQuery UI对话框组件 $.getScript("https://code.jquery.com/ui/1.13.2/dialog.min.js", function() { // 初始化对话框 $("#dialog").dialog({ // 对话框配置 }); }); });
- 优化动画效果:减少或禁用不必要的动画效果,可以提高性能。
// 禁用动画效果 $("#tabs").tabs({ show: null, // 禁用显示动画 hide: null // 禁用隐藏动画 });
组件初始化问题
问题:jQuery UI组件无法正确初始化或功能异常。
解决方案:
- 确保DOM已加载:在DOM完全加载后再初始化jQuery UI组件。
// 使用$(document).ready() $(document).ready(function() { $("#datepicker").datepicker(); }); // 或者使用简写形式 $(function() { $("#datepicker").datepicker(); });
- 检查选择器:确保选择器正确匹配要初始化的元素。
// 错误的选择器 $(".date-picker").datepicker(); // 如果元素使用的是id="datepicker" // 正确的选择器 $("#datepicker").datepicker();
- 避免重复初始化:确保不要多次初始化同一个组件。
// 检查组件是否已初始化 if (!$("#datepicker").hasClass("hasDatepicker")) { $("#datepicker").datepicker(); }
事件处理问题
问题:jQuery UI组件的事件无法正确触发或处理。
解决方案:
- 使用正确的事件名称:不同的组件有不同的事件名称,确保使用正确的事件。
// 日期选择器的事件 $("#datepicker").datepicker({ onSelect: function(dateText) { console.log("选择的日期: " + dateText); } }); // 对话框的事件 $("#dialog").dialog({ close: function() { console.log("对话框已关闭"); } });
- 使用事件委托:对于动态添加的元素,使用事件委托来处理事件。
// 使用事件委托处理按钮点击 $(document).on("click", ".dynamic-button", function() { console.log("动态按钮被点击"); });
- 正确使用事件对象:在事件处理函数中,正确使用事件对象和参数。
// 滑块的事件处理 $("#slider").slider({ slide: function(event, ui) { // ui.value包含当前滑块的值 console.log("滑块值: " + ui.value); } });
学习资源和进阶路径
要深入学习jQuery UI,以下是一些有用的学习资源和进阶路径:
官方文档
jQuery UI官方网站:https://jqueryui.com/
- 提供完整的组件演示、文档和下载
- 包含主题定制工具ThemeRoller
jQuery UI API文档:https://api.jqueryui.com/
- 详细的API参考,包括所有组件的选项、方法和事件
- 提供代码示例和使用说明
推荐教程
jQuery UI教程 - W3Schools
- 网址:https://www.w3schools.com/jqueryui/
- 提供基础教程和实例,适合初学者
jQuery UI教程 - Tutorialspoint
- 网址:https://www.tutorialspoint.com/jqueryui/
- 详细的教程和示例,涵盖所有主要组件
jQuery UI入门教程 - 菜鸟教程
- 网址:https://www.runoob.com/jqueryui/jqueryui-tutorial.html
- 中文教程,适合中文用户学习
书籍推荐
《jQuery UI Cookbook》by Adam Boduch
- 提供实用的jQuery UI解决方案和最佳实践
- 包含大量实例代码和详细解释
《jQuery UI in Action》by T.J. VanToll
- 深入介绍jQuery UI的各个方面
- 适合有一定基础的开发者
《jQuery UI 1.8: The User Interface Library for jQuery》by Dan Wellman
- 全面介绍jQuery UI 1.8版本的功能和用法
- 包含实际项目案例
社区资源
Stack Overflow
- 网址:https://stackoverflow.com/questions/tagged/jquery-ui
- 最大的程序员问答社区,可以找到各种jQuery UI问题的解决方案
jQuery UI论坛
- 网址:https://forum.jquery.com/using-jquery-ui
- 官方论坛,可以获取官方支持和与其他开发者交流
GitHub
- 网址:https://github.com/jquery/jquery-ui
- jQuery UI的源代码仓库,可以查看最新开发和提交问题
进阶学习路径
基础阶段
- 学习jQuery基础知识
- 了解jQuery UI的基本组件和用法
- 完成简单的UI组件实现
中级阶段
- 深入学习各个组件的选项、方法和事件
- 学习自定义主题和样式
- 实现复杂的交互功能
高级阶段
- 学习组件扩展和自定义
- 研究jQuery UI的源代码
- 开发自己的jQuery UI插件
专业阶段
- 掌握性能优化技巧
- 学习与其他前端框架的集成
- 参与开源项目贡献
实践项目建议
个人博客系统
- 使用jQuery UI的标签页、对话框和按钮组件
- 实现文章管理、评论系统等功能
任务管理应用
- 使用jQuery UI的进度条、日期选择器和拖放功能
- 实现任务创建、编辑和进度跟踪
产品展示网站
- 使用jQuery UI的折叠面板、轮播图和菜单组件
- 创建美观的产品展示和导航界面
数据可视化仪表板
- 使用jQuery UI的滑块、进度条和按钮组件
- 创建交互式数据展示和控制界面
通过以上学习资源和实践项目,你可以逐步掌握jQuery UI的使用,从初学者成长为专业的前端开发者。记住,实践是最好的学习方式,不断尝试和解决问题将帮助你更好地理解和应用jQuery UI。