如何使嵌套在jQuery UI对话框中的div随着对话框一起调整大小?

13

我的jQuery UI对话框包含两个div元素。其中一个具有固定高度,应始终对齐在对话框底部。另一个应占据其余空间。

enter image description here

基本上,我希望所有以蓝色显示的尺寸在调整大小时保持不变。换句话说,红色div在两个方向调整大小,但绿色div保持其高度。

在 jQuery UI 或仅使用普通 CSS 中实现这一点的最简单方法是什么?

3个回答

6
我找到了一种不使用任何JavaScript的方法来实现这个,甚至不涉及任何hack;只是纯正常的CSS3。试验结果在这里:http://jsfiddle.net/nty5K/16/ 基本上,两个div都是“position: absolute”,每个边都使用“top”,“bottom”,“left”和“right”属性单独固定。顶部的div指定了所有四个位置,使其随着容器调整大小同时保持与容器每个边缘的确切距离。底部div有三个位置被固定,而顶部则仅通过固定高度间接定义。
在实践中,div需要放置到具有“position: relative”的包装器div中,否则顶部/底部的div将相对于body元素定位。
尚不确定浏览器兼容性如何,但这在Firefox 10、IE9和Chrome 17中很好地工作。未在早期版本中测试。

这显然是正确的做法。恭喜你找到了它。令人惊讶的是,没有其他人想到过。也许StackOverflow不再是最好的答案之所在了 - 只需看看这里发布的所有无用回复... - Timwi
仅供娱乐,这里有一个fiddle http://jsfiddle.net/cPwqN/3/,其中包含自动调整大小的顶部停靠和底部停靠元素,并使用一些JavaScript来设置中间元素的高度。 - Roman Starkov
一眼看上去这在IE 8和7中可以工作,但我怀疑随着添加更多内容,7会开始崩溃。我的大部分用户仍在使用7(我们没有迁移到9),而7的定位错误是我首次通过JavaScript / JQuery解决此类问题的原因。 - Rozwel

1

公司防火墙正在阻止图像,因此我根据其他评论猜测您想要的内容。

编辑: 现在我可以看到您想要什么,我已经相应地更新了我的fiddle。为了完整起见,包括下面的代码。

我会编写一个函数来计算对话框的大小,减去固定div的高度,并将动态div的高度设置为这个计算值。然后,我会将调用此函数的绑定绑定到对话框的resize事件上。这里是一个fiddle,可能需要针对您的确切布局进行一些微调,但应该很接近。

值得注意的一个陷阱是,一些浏览器可能无法正确计算,而它们正在进行滚动/调整大小事件,使用setTimeout排队计算以在调整大小事件完成后解决问题,尽管它使更改在调整大小正在进行时有点跳跃。请参见此问题和答案以获取详细信息。

function SetDivHeight() {
    var $DynamicDiv = $('div.dynamic');
    var $FixedDiv = $('div.fixed');
    var $Container = $(window); //Update for containing element

/*Calculate the adjustment needed to account for the margin and 
border of the dynamic div.*/
    var HeightAdjustment = $DynamicDiv.outerHeight(true) - $DynamicDiv.height();

/*Get the values of the top and bottom margins which overlap 
between the two divs.*/
    var DynamicBottomMargin = parseInt($DynamicDiv.css('marginBottom'));
    var FixedTopMargin = parseInt($FixedDiv.css('marginTop'));

/*Adjust for the overlapping top/bottom margin by subtracting 
which ever is smaller from the adjustment value.*/
    if (DynamicBottomMargin >= FixedTopMargin) {
        HeightAdjustment -= FixedTopMargin;
    } else {
        HeightAdjustment -= DynamicBottomMargin;
    }


/*subtract the height of the fixed div from the height of the 
container, subtract the calculated height adjustment from that 
value, and set the result as the height of the dynamic div.*/
    $DynamicDiv.height(($Container.height() - $FixedDiv.outerHeight(true)) - 
HeightAdjustment);
/*May need to use $Container.innerHeight instead, if container 
is not a window element.*/
}

var t;

function QueueSetDivHeight() {
    if (t) {
        clearTimeout(t);
    }
    t = setTimeout(function() {
        SetDivHeight();
    }, 0);
}

$(document).ready(function() {
    SetDivHeight();
    $(window).resize(QueueSetDivHeight);
    //Bind to resize of container element instead/as well
});

-2

只需要 CSS... 看看吧!

给容器设置一个 margin,并给底部固定的 div 设置一个 margin-top。不需要 jQuery。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接