jQuery UI Selectable(选择)实例
jQuery UI 的Selectable交互允许用户通过鼠标拖拽(套索 lasso)或 Ctrl+点击来多选列表中的元素,常用于文件管理器、图片库、任务列表等多选场景。选中元素会添加ui-selected类,便于自定义样式。
推荐查看官方演示:https://jqueryui.com/selectable/
下面提供几个渐进实例,从基础到高级,代码使用最新 CDN,可直接复制到 HTML 文件测试。
1.基础选择示例(有序列表)
用鼠标拖拽框选或 Ctrl+点击单个项目。
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>jQuery UI Selectable 基础示例</title><linkrel="stylesheet"href="//code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css"><scriptsrc="//code.jquery.com/jquery-3.6.0.min.js"></script><scriptsrc="//code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script><style>#selectable .ui-selecting{background:#FECA40;}#selectable .ui-selected{background:#F39814;color:white;}#selectable{list-style-type:none;margin:0;padding:0;width:300px;}#selectable li{margin:3px;padding:10px;font-size:1.2em;height:30px;}</style></head><body><olid="selectable"><liclass="ui-widget-content">项目 1</li><liclass="ui-widget-content">项目 2</li><liclass="ui-widget-content">项目 3</li><liclass="ui-widget-content">项目 4</li><liclass="ui-widget-content">项目 5</li><liclass="ui-widget-content">项目 6</li></ol><script>$(function(){$("#selectable").selectable();});</script></body></html>2.网格选择示例(图片或方块)
常用于图片库多选。
<divid="selectable-grid"style="width:400px;height:300px;background:#eee;padding:10px;"><divclass="item ui-widget-content"style="width:80px;height:80px;float:left;margin:5px;background:#4CAF50;color:white;text-align:center;line-height:80px;">1</div><divclass="item ui-widget-content"style="width:80px;height:80px;float:left;margin:5px;background:#2196F3;color:white;text-align:center;line-height:80px;">2</div><divclass="item ui-widget-content"style="width:80px;height:80px;float:left;margin:5px;background:#FF9800;color:white;text-align:center;line-height:80px;">3</div><!-- 更多项... --></div><script>$("#selectable-grid").selectable({filter:".item"// 只选择 class="item" 的元素});</script>3.选项与事件(filter、tolerance、selected/stop)
filter:指定可选择子元素。tolerance: "fit":只有完全框住才选中。- 事件:获取选中项。
<p>已选中:<spanid="feedback">无</span></p><script>$("#selectable").selectable({tolerance:"fit",// 完全框住才选中stop:function(){varresult=$("#feedback").empty();$(".ui-selected",this).each(function(){result.append($(this).text()+" ");});}});</script>4.取消选择与自定义
按 Esc 取消选择,或添加cancel选项排除某些元素。
<script>$("#selectable").selectable({cancel:".no-select",// class="no-select" 的元素不可选selected:function(event,ui){console.log("选中: "+ui.selected.textContent);},unselected:function(event,ui){console.log("取消选中: "+ui.unselected.textContent);}});</script>Selectable 常与 Sortable 结合实现可拖拽排序的多选列表,或用于批量操作(如删除选中图片)。如果你需要显示选中项的完整示例、与按钮结合的批量删除,或图片网格示例,请提供更多细节!