jQuery UI Droppable(放置)实例
jQuery UI 的Droppable交互允许将元素定义为“可放置目标”,通常与Draggable(拖动)结合使用,实现拖拽放置功能。常用于购物车、垃圾桶、排序列表、回收站等场景。
推荐查看官方演示:https://jqueryui.com/droppable/
下面提供几个渐进实例,从基础到高级,代码使用最新 CDN,可直接复制到 HTML 文件测试。
1.基础拖拽放置示例
拖动小方块到目标区域,放置时触发提示。
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>jQuery UI Droppable 基础示例</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:100px;height:100px;background:#4CAF50;color:white;text-align:center;line-height:100px;cursor:move;}#droppable{width:200px;height:200px;background:#f44336;color:white;text-align:center;line-height:200px;margin-top:20px;}</style></head><body><divid="draggable"class="ui-widget-content">拖动我</div><divid="droppable"class="ui-widget-header">放到这里</div><script>$(function(){$("#draggable").draggable();$("#droppable").droppable({drop:function(event,ui){alert("放置成功!");$(this).addClass("ui-state-highlight").text("已放置!");}});});</script></body></html>2.hover 效果与 accept(仅接受特定元素)
activeClass和hoverClass:添加悬停/激活样式。accept:只允许特定 draggable 元素放置(如不同类)。
<divid="draggable1"class="small">小方块(可放置)</div><divid="draggable2"class="big">大方块(不可放置)</div><divid="droppable2">仅接受小方块</div><style>.small{width:80px;height:80px;background:#2196F3;}.big{width:120px;height:120px;background:#FF9800;}#droppable2{width:250px;height:250px;background:#9C27B0;margin-top:20px;}</style><script>$(".small, .big").draggable();$("#droppable2").droppable({accept:".small",// 只接受 class="small" 的元素activeClass:"ui-state-active",// 可拖入时样式hoverClass:"ui-state-hover",// 悬停时样式drop:function(event,ui){$(this).text("小方块放置成功!");}});</script>3.tolerance(容忍度)与 revert(回弹)
tolerance: "pointer"等:控制触发放置的条件(fit、intersect、pointer、touch)。- 与 draggable 的
revert: "invalid"结合:无效放置时回弹。
<divid="draggable3">拖动我(无效时回弹)</div><divid="droppable3">放置目标(pointer 模式)</div><script>$("#draggable3").draggable({revert:"invalid"// 无效放置回弹});$("#droppable3").droppable({tolerance:"pointer",// 鼠标指针进入即触发drop:function(){alert("成功放置!");}});</script>4.事件回调(over、out、drop 等)
完整事件:activate、deactivate、over、out、drop。
<script>$("#droppable4").droppable({over:function(event,ui){console.log("进入放置区");$(this).css("border","4px dashed green");},out:function(event,ui){console.log("离开放置区");$(this).css("border","");},drop:function(event,ui){console.log("放置完成");ui.draggable.appendTo(this);// 将拖动元素移动到目标内}});</script>Droppable 常与 Draggable、Sortable 结合实现复杂交互(如回收站删除:放置到垃圾桶后移除元素)。如果你需要购物车示例、回收站效果,或与 Sortable 结合的列表排序,请提供更多细节!