如何调整浮动元素的大小,使其总宽度始终为父容器的 100%?

How to resize floated elements so that their total width is always 100% of a parent container?

我在容器中有三个 div 向左浮动,每个 div 占据容器宽度的 33.3%(1/3)。我希望能够调整其中任何一个的大小,这将反向调整最近的兄弟姐妹的大小,以便所有三个 divs 的宽度始终为容器宽度的 100%。

jquery 可调整大小调用:

var containerWidth = $("#container").width();
$(".box").resizable({
handles: "e",
containment: "#container",
resize: function(e,ui){
    var totalSize = ui.size.width;
    ui.element.siblings(".box").each(function(){
    totalSize = totalSize + $(this).width();
  });
  var direction = totalSize > containerWidth ? -1 : 1;
  var nextBox = ui.element.next(".box");
  var nextBoxWidth = nextBox.width();
  nextBox.width(nextBoxWidth + direction);
}
});

请使用这个 jsfiddle 查看我遇到的问题:

jsfiddle

在示例中,我正在获取容器的宽度并将其与调整大小事件期间框的总大小进行比较。这应该告诉我当前盒子的尺寸是缩小还是放大,因此最近的兄弟姐妹应该放大还是缩小。这显然是行不通的。

有谁知道完成我想做的事情的方法吗?也许有办法在插件中使用 alsoResize 选项?

您只是将 nextBox 宽度增加了 +/-1px。我认为您应该用以下内容替换该行:

var extraWidth = containerWidth - totalSize;
nextBox.width(nextBoxWidth + extraWidth);

第一行告诉你调整后的自由space有多宽;然后增加相同数量的 nextBox 宽度(参见 here