jQuery UI Draggable(拖动)实例
jQuery UI 的 Draggable 交互允许将元素变为可拖动,常用于实现拖拽排序、窗口拖动、游戏交互等。基本用法简单,但支持丰富选项和事件。
推荐查看官方演示:https://jqueryui.com/draggable/
下面提供几个渐进实例,从基础到高级,代码使用最新 CDN(jQuery 3.6 + jQuery UI 1.13),可直接复制到 HTML 文件测试。
1. 基础拖动示例
最简单的可拖动元素。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI Draggable 基础示例</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="//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>
<div id="draggable" class="ui-widget-content">拖动我!</div>
<script>
$(function() {
$("#draggable").draggable();
});
</script>
</body>
</html>
2. 常见选项示例(helper、revert、cursor 等)
helper: "clone":拖动时显示克隆副本,原元素不动。revert: "invalid":未放到有效区域时自动回弹。cursor: "move":改变鼠标样式。
<div id="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:吸附到指定元素。
<div style="width: 400px; height: 300px; border: 2px solid #000; position: relative;">
<div id="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。
<div id="draggable4" style="width: 200px; height: 100px; background: #2196F3; color: white;">
<div class="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 结合的完整拖拽放置示例,或特定场景(如排序列表),请告诉我!