Jquery ui draggable – 自动调整父级包含
对不起,我的英语不是很好。 我希望我的容器元素resize以始终包含其子元素。
访问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); } } } ); });
$(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;
您可以使用以下内容来确定shouldHeight
– 基本上:
- 使用选择器来获取所有可拖动的东西
- 获得它的高度,并将其与您现有的相比较
- 设置高度。
以下是如何:
var shouldHeight = 0; $(".ui-draggable").each(function () { var draggeePosition = $(this).position(); if (shouldHeight < draggeePosition.top + $(this).height() + 15) { shouldHeight = draggeePosition.top + $(this).height() + 15; } });
小提琴: http : //jsfiddle.net/LakYy/3/
基于@caspian的解决方案,您可能会发现这种变化可以在许多可拖动的情况下更好地扩展。 同样的事情,但每件物品只找到一次dom位置:
$(".ui-draggable").each(function () { var draggeeHeight = $(this).position().top + $(this).height() + 15; if (shouldHeight < draggeeHeight) { shouldHeight = draggeeHeight; }; }); if ($parent.height() != shouldHeight) { $parent.height(shouldHeight); }
我也需要这个项目,这里是小提琴http://jsfiddle.net/genkilabs/WCw8E/2/
对于@coding_idiot,如果你使用overflow-x: scroll;
,你要问的是默认行为overflow-x: scroll;