如何配置jQuery Sortable实现仓库到店铺单向拖拽并禁用店铺间拖拽?
Hey there! Let's sort out that drag-and-drop constraint issue you're facing. The problem with your current code is that your connectWith setup creates unintended links between your store elements, which is why they can still drag items between each other. Let's fix this with clear, targeted settings.
The Root of the Problem
Your original code applies the same sortable configuration to both the warehouse (.sender) and stores (#receiver1, #receiver2), using connectWith: $('#receiver2,#receiver1').not(this). This ends up making each store connect to the other, allowing cross-store drags. We need to split the configuration into two separate sets: one for the warehouse (allowed to send items) and one for the stores (only allowed to receive items from the warehouse, no outgoing drags).
Step-by-Step Solution
First, let's clean up selectors for maintainability:
- Keep your warehouse element with the
.senderclass - Add a shared
.storeclass to all your store elements (you can keep their individual IDs too, if needed)
Here's the corrected code:
// Initialize the warehouse (sender) - can drag items to stores $('.sender').sortable({ // Only connect to store elements connectWith: '.store', // Allow all child elements to be draggable items: '> *', // Revert item to original position if dropped in invalid area revert: true }).disableSelection(); // Initialize all stores - can only receive items from warehouse, no outgoing drags $('.store').sortable({ // Do NOT connect to any other sortable elements connectWith: false, // Disable dragging of items inside the store (prevents any outgoing drags) items: '', // Safety check: only accept items coming from the warehouse receive: function(event, ui) { if (!ui.sender.hasClass('sender')) { // Cancel the drag if the item comes from a non-warehouse source ui.sender.sortable('cancel'); } } }).disableSelection();
What Each Part Does
- Warehouse (
.sender): We explicitly setconnectWith: '.store'so its items can only be dropped into store elements. Therevertoption ensures items bounce back if dropped anywhere else. - Stores (
.store):connectWith: falseremoves any connection to other sortables, so stores can't send or receive from each other.items: ''disables dragging of any items inside the store — once an item is in a store, it can't be moved at all (aligning with your "no dragging back to warehouse or between stores" rule).- The
receiveevent acts as a safety net: if any item tries to drop into a store from a non-warehouse source, it cancels the drag immediately.
Final Result
This setup enforces exactly what you need:
- ✅ Items can be dragged from the warehouse to any store
- ❌ Items cannot be dragged from stores back to the warehouse
- ❌ Items cannot be dragged between different stores
内容的提问来源于stack exchange,提问作者Daniele Zerosi

