jQuery UI Draggable(拖动)实例
jQuery UI 的Draggable交互允许将元素变为可拖动,常用于实现拖拽排序、窗口拖动、游戏交互等。基本用法简单,但支持丰富选项和事件。
推荐查看官方演示:https://jqueryui.com/draggable/
下面提供几个渐进实例,从基础到高级,代码使用最新 CDN(jQuery 3.6 + jQuery UI 1.13),可直接复制到 HTML 文件测试。
1.基础拖动示例
最简单的可拖动元素。
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>jQuery UI Draggable 基础示例</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>#draggable{width:120px;height:120px;padding:20px;background:#4CAF50;color:white;text-align:center;cursor:move;}</style></head><body><divid="draggable"class="ui-widget-content">拖动我!</div><script>$(function(){$("#draggable").draggable();});</script></body></html>2.常见选项示例(helper、revert、cursor 等)
helper: "clone":拖动时显示克隆副本,原元素不动。revert: "invalid":未放到有效区域时自动回弹。cursor: "move":改变鼠标样式。
<divid="draggable2"class="ui-widget-content">克隆拖动(回弹)</div><script>$("#draggable2").draggable({helper:"clone",// 拖动克隆revert:"invalid",// 无效放置时回弹cursor:"move",// 鼠标样式opacity:0.7// 拖动时半透明});</script>3.限制拖动范围(axis、containment、grid、snap)
axis: "x"或"y":仅水平/垂直拖动。containment: "parent":限制在父容器内。grid: [50, 50]:网格吸附,每 50px 一步。snap: true:吸附到指定元素。
<divstyle="width:400px;height:300px;border:2px solid #000;position:relative;"><divid="draggable3">网格拖动(限制在容器内)</div></div><script>$("#draggable3").draggable({containment:"parent",// 限制在父容器grid:[50,50],// 网格吸附snap:true,// 吸附到其他元素(需指定snap目标)snapTolerance:20// 吸附距离阈值});</script>4.拖动事件与手柄(handle、delay、distance)
handle:仅指定区域可拖动。delay: 300:延迟 300ms 开始拖动(防误触)。distance: 20:鼠标移动 20px 后开始拖动。- 事件:start、drag、stop。
<divid="draggable4"style="width:200px;height:100px;background:#2196F3;color:white;"><divclass="handle"style="background:#f44336;padding:10px;cursor:move;">仅此区域拖动</div><p>内容区域不可拖动</p></div><script>$("#draggable4").draggable({handle:".handle",// 仅手柄拖动delay:300,// 延迟开始distance:20,// 移动距离阈值start:function(){console.log("开始拖动");},drag:function(){console.log("拖动中");},stop:function(){console.log("停止拖动");}});</script>Draggable 常与Droppable(放置)、Sortable(排序)结合使用,实现更复杂交互。如果你需要与 Droppable 结合的完整拖拽放置示例,或特定场景(如排序列表),请告诉我!