jquery Draggable 拖动效果
封面图
•
2025-11-22
•
jQuery
244
0
0
0
jQuery 的 `draggable` 是 jQuery UI 提供的一个功能,用于让元素可以被拖动。它非常方便地实现了拖拽效果,常用于网页中的拖放交互。 --- ## 📌 一、基本用法 ### 1. 引入必要的库 你需要先引入 **jQuery** 和 **jQuery UI** 的库文件: ```html <!-- 引入 jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- 引入 jQuery UI --> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> ``` --- ### 2. HTML 示例 ```html <div id="draggable" style="width: 100px; height: 100px; background-color: lightblue;"> 拖我 </div> ``` --- ### 3. JavaScript 初始化 draggable ```javascript $(function() { $("#draggable").draggable(); }); ``` 这样你就可以拖动这个 `div` 了。 --- ## 🎨 二、常用选项(Options) | 属性 | 描述 | |------|------| | `axis` | 限制拖动方向(`x` 或 `y`) | | `containment` | 限制拖动范围(如 `"parent"` 或 `#container`) | | `cursor` | 鼠标样式(如 `"move"`) | | `revert` | 拖动结束后是否返回原位(`true` / `false`) | | `opacity` | 拖动时的透明度(0~1) | ### 示例: ```javascript $("#draggable").draggable({ axis: "x", // 只能左右拖动 containment: "parent", // 限制在父容器内 cursor: "move", opacity: 0.7, revert: true }); ``` --- ## 🧩 三、事件监听(Events) | 事件 | 描述 | |------|------| | `start` | 开始拖动时触发 | | `drag` | 拖动过程中持续触发 | | `stop` | 拖动结束时触发 | ### 示例: ```javascript $("#draggable").draggable({ start: function(event, ui) { console.log("开始拖动"); }, drag: function(event, ui) { console.log("正在拖动:", ui.position); }, stop: function(event, ui) { console.log("拖动结束"); } }); ``` --- ## ✅ 四、拖动到其他元素(结合 droppable) 如果你想实现“拖动 + 放置”功能,可以结合 `droppable`。 ### 示例: ```html <div id="draggable" style="width: 100px; height: 100px; background-color: lightblue;">拖我</div> <div id="droppable" style="width: 200px; height: 200px; background-color: lightgreen; margin-top: 20px;">放置到这里</div> ``` ```javascript $(function() { $("#draggable").draggable(); $("#droppable").droppable({ drop: function(event, ui) { alert("成功放置!"); } }); }); ``` --- ## 📝 五、总结 - `draggable()` 让元素可拖动。 - 可以通过 `options` 控制行为。 - 结合 `droppable()` 实现拖放交互。 - 适用于简单的拖拽界面设计。 --- 如果你有更具体的需求,比如拖动排序、拖动到特定区域、拖动动画等,欢迎继续提问!
上一篇:
jQuery this 和 Selector $(this:first-child).css 介绍
下一篇:
jQuery :first-child 选择器
标题录入,一次不能超过6条
留言
评论