咨询含if-else判断的jQuery Droppable拖拽代码是否可行
Hey there! No worries about your English at all—let's get this drag-and-drop behavior working exactly how you want it.
First, let's break down the issues in your current code:
- You've got invalid syntax trying to wrap the
dropcallback in anifstatement directly inside the droppable configuration object. Thedropshould be a function property of that object. - You missed the
#in$('drag1')—jQuery needs that to select an element by ID. - To disable a draggable element correctly, you need to use the
optionmethod:draggable('option', 'disabled', true)instead of just passingdisabled.
Since you already set accept: '#drag1', the drop event will only trigger when #drag1 is dropped onto #drop1. But if you wanted to add extra checks (or if you expand the accepted elements later), we can include conditional logic inside the drop function.
Here's the corrected code that does what you want:
$('#drop1').droppable({ accept: '#drag1', drop: function(event, ui) { // Check if the dropped element is #drag1 (though accept already ensures this) if (ui.draggable.attr('id') === 'drag1') { $(this).css('background-color', 'green'); $('#drag1').draggable('option', 'disabled', true); } else { $(this).css('background-color', 'red'); } }, // Optional: Reset background if the element is dragged away without dropping out: function() { $(this).css('background-color', ''); } });
Let me explain what's happening here:
- The
dropcallback runs only when an accepted element is dropped. We double-check the ID just for clarity (you could skip this if you're sureacceptis doing its job). - When
#drag1is dropped, we turn#drop1green and disable the draggable element. - If for some reason a non-accepted element gets through (unlikely with your
acceptsetting), it turns red. - The optional
outhandler resets the background color if the dragged element is pulled away without being dropped, which makes the behavior feel more intuitive.
If you wanted to handle cases where something else is dragged over (not just dropped), you could also use the over and out events to change the background as the element hovers.
内容的提问来源于stack exchange,提问作者Paul Tanné

