我试图将背景div的高度与前面div的组合高度相匹配。我使用简单的jQuery高度函数,它有点工作:
var originalHeight = $("#topbg").height() + $("#menurowbg").height() + $("#headerbg").height() + $("#contentareabg").height() + $("#footerbg").height();
$("#wrapper").height(originalHeight);
问题是,如果其中一个div被调整大小以保持匹配,高度需要动态改变。我试图把setTimeout函数,但失败了。我显然错过了什么,但我不明白。请帮助这个jQuery新手。下面是我当前的代码:
var originalHeight = $("#topbg").height() + $("#menurowbg").height() + $("#headerbg").height() + $("#contentareabg").height() + $("#footerbg").height();
setTimeout function checkHeight() {
if(originalHeight < ($("#topbg").height() + $("#menurowbg").height() + $("#headerbg").height() + $("#contentareabg").height() + $("#footerbg").height()))
{
originalHeight = $("#topbg").height() + $("#menurowbg").height() + $("#headerbg").height() + $ ("#contentareabg").height() + $("#footerbg").height();
}
}, 500);
$("#wrapper").height(originalHeight);
有三种情况:
1)使用setInterval()
而不是setTimeout()
每X毫秒执行代码:
setInterval(function() {
setContainerSize();
}, 1000);
示例:http://jsfiddle.net/XWmdL/3/
2)包含div的div是正在调整大小的div的父div。在这种情况下,您不必将所有高度加在一起并重置容器的高度。你可以将容器的宽度和高度属性设置为auto
:
#container {
width: auto;
height: auto;
}
示例:http://jsfiddle.net/XWmdL/1/
3)如果你的子div在窗口大小改变时正在调整大小,你需要使用$(window).resize()
事件。在下面的示例中更改查看窗口的大小,您将看到红色背景的大小随着黄色div的变化而变化。
示例:http://jsfiddle.net/XWmdL/2/
希望这对你有帮助!
首先条件是错误的
setTimeout function checkHeight() {
if(originalHeight < (jQuery("#topbg").height() + jQuery("#menurowbg").height() + jQuery("#headerbg").height() + jQuery("#contentareabg").height() + jQuery("#footerbg").height())) {
originalHeight = jQuery("#topbg").height() + jQuery("#menurowbg").height() + jQuery("#headerbg").height() + jQuery("#contentareabg").height()+jQuery("#footerbg").height();
jQuery("#wrapper").height(originalHeight);
}, 500);