This question already has answers here:
JqueryUI Draggable - Auto resize parent container
                                
                                    (2个答案)
                                
                        
                                4年前关闭。
            
                    
对不起,我的英语不太好。我希望我的容器元素能够调整大小以始终包含其子元素。

访问jsfiddle.net/datakolay/LakYy/

$(document).ready(function() {
    var
        $document = $(document),
        $parent = $("#parent"),
        $container = $(".container", $parent),
        offset = $container.offset(),
        scrollbarSafety = 15;

    $container.height($document.height() - offset.top - scrollbarSafety);

    $("#eleman,#eleman2")
            .draggable(
            {
                containment: $container,
                drag:
                    function(event, ui)
                    {
                        var
                            $draggee = $(this),
                            draggeePosition = $draggee.position(),

                            shouldHeight = draggeePosition.top + $draggee.height() + 15;

                        if($parent.height() < shouldHeight)
                        {
                            $parent.height(shouldHeight);
                        }

                        if($parent.height() > shouldHeight)
                        {
                            $parent.height(shouldHeight);
                        }

                    }
            }
        );
});

最佳答案

http://jsfiddle.net/LakYy/5/

$(document).ready(function() {
    var
        $document = $(document),
        $parent = $("#parent"),
        $container = $(".container", $parent),
        offset = $container.offset(),
        scrollbarSafety = 15;

    $container.height($document.height() - offset.top - scrollbarSafety);

    $("#eleman,#eleman2")
            .draggable(
            {
                containment: $container,
                drag:
                    function(event, ui)
                    {
                        var shouldHeight = getdraggablemaxheight();

                        if($parent.height() < shouldHeight)
                        {
                            $parent.height(shouldHeight);
                        }

                        if($parent.height() > shouldHeight)
                        {
                            $parent.height(shouldHeight);
                        }

                    }
            }
        );
});

function getdraggablemaxheight() {
    var $parent = $("#parent"),
        $container = $(".container", $parent),
        maxheight = 0,
        currentheight = 0,
        currentposition;

    $container.children().each(function(index, element) {
        currentposition = $(element).position();
        currentheight = currentposition.top +  + $(element).height() + 15;
        if(currentheight > maxheight)
            maxheight = currentheight;
    });

    return maxheight;

09-18 08:07