如何使用jQuery实现父级容器的拖拽交换功能(已支持子元素交换)
实现父容器与子元素的双向拖拽交换
我看了你的代码,要同时支持子元素在容器间拖拽和父容器整体拖拽交换其实只需要调整一下结构和jQuery UI Sortable的配置就可以搞定,下面是具体的修改方案:
1. 调整HTML结构
给三个父容器(tab1/tab2/tab3)添加一个共同的外层容器,同时给每个父容器加上统一的class(方便后续选择器定位):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet"/> <script src="https://code.jquery.com/ui/1.8.24/jquery-ui.min.js" integrity="sha256-UOoxwEUqhp5BSFFwqzyo2Qp4JLmYYPTHB8l+1yhZij8=" crossorigin="anonymous"></script> <!-- 新增外层容器,用于承载父容器的排序 --> <div id="tabs-container"> <div id="tab1" class="tab"> <div id="sort1"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div> </div> <div id="tab2" class="tab"> <div id="sort2"> <div>5</div> <div>6</div> <div>7</div> <div>8</div> </div> </div> <div id="tab3" class="tab"> <div id="sort3"> <div>9</div> <div>10</div> <div>11</div> <div>12</div> </div> </div> </div>
2. 更新CSS样式
添加父容器的拖拽样式,同时补充占位符样式提升拖拽体验:
/* 子元素样式保持你的原有配置 */ .ui-sortable div div { border:1px solid; margin:6px; font-size:1.3em; padding:5px; width:160px; background-color:#F0E3F3; padding-left:20px; } #sort1, #sort2, #sort3 { float:left; padding: 10px; border: 1px solid black; margin: 10px; border-radius:10px; } #sort2 div { background-color:#FBFED6; } /* 新增父容器样式 */ .tab { float: left; margin: 10px; padding: 10px; border: 1px solid #999; border-radius: 8px; background: #f9f9f9; cursor: move; /* 提示用户该容器可拖拽 */ } /* 清除外层容器浮动,避免高度塌陷 */ #tabs-container::after { content: ""; display: table; clear: both; } /* 拖拽时的占位符样式,让拖拽位置更直观 */ .tab-placeholder { border: 2px dashed #ccc; width: 200px; height: auto; float: left; margin: 10px; border-radius: 8px; }
3. 修改JS配置
移除原来单独给tab1/tab2/tab3设置的sortable,转而给外层容器设置父容器排序,同时保留子元素的拖拽配置:
$(document).ready(function() { // 保留子元素的拖拽交换逻辑(你的原有代码) $("#sort1").sortable({ connectWith: "#sort2, #sort3" }); $("#sort2").sortable({ connectWith: "#sort3, #sort1" }); $("#sort3").sortable({ connectWith: "#sort2, #sort1" }); // 新增父容器的拖拽交换逻辑 $("#tabs-container").sortable({ items: ".tab", // 指定可排序的元素是带有.tab类的父容器 placeholder: "tab-placeholder", // 拖拽时显示占位符 cursor: "move" }); });
效果说明
这样修改后,你就能同时实现两种拖拽功能:
- 子元素拖拽:比如把
sort1里的4拖到sort2中,和7交换位置 - 父容器拖拽:比如把整个
tab1拖到tab3的右侧,交换两个父容器的顺序
完全满足你想要的交互需求~
内容的提问来源于stack exchange,提问作者Redair
相关产品推荐
相关产品推荐

