在“拖放”面板中限制最大元素

时间:2011-05-06 12:09:23

标签: jquery-ui

我的网站上有一个可排序的面板(jQuery UI),但需要将每列中的元素数量限制为最多12个。

我尝试了一些东西,但似乎无法让它发挥作用。我需要看看'i'是否为12或更高,如果是,请不要更新,但我似乎无法做到!

任何人都有任何建议或能以正确的方式推动我吗?

jQuery在下面!

function updateWidgetData(){
    var items=[];
    $('.column').each(function(){
        var columnId=$(this).attr('id');
        $('.dragbox', this).each(function(i){
            var collapsed=0;
            if($(this).find('.dragbox-content').css('display')=="none")
                collapsed=1;
            var item={
                id: $(this).attr('ID'),
                collapsed: collapsed,
                order : i,
                column: columnId
            };
            items.push(item);
        });
    });
    var sortorder={ items: items };

    //Pass sortorder variable to server using ajax to save state

    $.post('includes/updatePanels.php', 'data='+$.toJSON(sortorder), function(response){
        if(response=="success")
            $("#console").html('<div class="success">Your preferences have been saved</div>').hide().fadeIn(1000);
        setTimeout(function(){
            $('#console').fadeOut(1000);
        }, 2000);
    });
}

1 个答案:

答案 0 :(得分:15)

Sortables

对于已连接的可排序,解决方案是在拖动开始时计算每个可排序元素,并禁用具有最大允许元素数的元素。我们需要排除当前的sortable,因此我们可以重新排序其中的项目并允许拖动当前元素。

这里的问题是,如果我们对任何可排序的事件执行上述操作,则已经太晚了,禁用它们将不会产生任何影响。解决方案是将检查绑定到项目本身的 mousedown 事件,这将在sortable获得任何控制之前触发。我们还需要在拖动停止时重新启用所有可排序项。

看一下这个示例,使用<ul>个可排序项与<li>项,每个可排序项中的最大项数为3:http://jsfiddle.net/qqqm6/10/

$('.sort').sortable({
    revert: 'invalid',
    connectWith: '.sort',
    stop: function(){
        // Enable all sortables
        $('.sort').each(function(){
            $(this).sortable('enable');
        });
    }
});

$('.sort li').mousedown(function(){
    // Check number of elements already in each sortable
    $('.sort').not($(this).parent()).each(function(){
        var $this = $(this);

        if($this.find('li').length >= 3){
            $this.sortable('disable');
        } else {
            $this.sortable('enable');
        }
    });
})

Draggables和droppables

理论很简单,解决方案有点棘手,jQuery UI中应该有一个合适的选项来取消drop上的操作。如果有,但我错过了什么,请告诉我。

无论如何,这里是你如何检查drop事件中的最大计数(在这个例子中最多为4):

$('.drag').draggable({
    revert: 'invalid',
    stop: function(){
        // Make it properly draggable again in case it was cancelled
        $(this).draggable('option','revert','invalid');
    }
});

$('.drop').droppable({
    drop: function(event,ui){
        var $this = $(this);

        // Check number of elements already in
        if($this.find('.drag').length >= 4){
            // Cancel drag operation (make it always revert)
            ui.draggable.draggable('option','revert',true);
            return;
        }

        // Put dragged item into container
        ui.draggable.appendTo($this).css({
            top: '0px',
            left: '0px'
        });

        // Do whatever you want with ui.draggable, which is a valid dropped object
    }
});

请参阅此小提琴:http://jsfiddle.net/qqqm6/

相关问题