[英]Matching div height to combined height of other divs
我正在嘗試將背景div的高度與前面的div的組合高度匹配。 我使用了簡單的jQuery height函數,它的工作原理是:
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的父級。 在這種情況下,您不必將所有高度加在一起就可以重置容器的高度。 您可以將容器的width和height屬性設置為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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.