jQuery draggable revert based on condition

前端 未结 2 1691
日久生厌
日久生厌 2020-12-16 23:36

I am having an issue related jQuery draggable and droppable. Here is description something what I want to do.

First: I have two divs. One is &

相关标签:
2条回答
  • 2020-12-16 23:47

    You can use the accept option which takes a function to do this much easier, like this:

    $("#selected ul").droppable({
        accept: function() {
            return $("#selected li").length < 5;
        }
    });
    

    You can test it out here. When you drag elements out, the .length goes down and it'll accept elements again...no reason to get any more complicated :)

    0 讨论(0)
  • 2020-12-17 00:03

    First of all, setting revert to false, will disable the revert function entirely. As you point out, you'll be able to drop the draggables anywhere. What you usually want is revert: 'invalid' which means that it'll revert whenever it's dropped on anything that isn't a droppable that accepts it.

    What you want to do ought to be something like this:

    $('#selected').droppable({
        drop: function() {
    
           // since you're doing a full re-calc every time, this doesn't need to be global
           var total = $("#selected li").length;
    
           if(total >= 5) {
    
               // once you've reached five, simply don't accept any more elements
               // the rest will revert if dropped here
               $('#selected').droppable('disable');
           }
        }
    });
    
    0 讨论(0)
提交回复
热议问题