2011-01-28 82 views
3

給出一個網頁div像<div id="rightRail>xxx</div>jQuery的-given一個div,擴展div的高度達到谷底

是否有可能一些如何神奇地作出broswer載荷div的高度調整/調整,這樣的高度到達窗戶的底部?如果div位於頁面的頂部,它會更容易,但它不是。感謝

+0

http://stackoverflow.com/questions/1443465/jquery-dynamic-div-height可能有助於 – 2011-01-28 06:37:56

回答

16

您需要.offset()help頂部值和innerHeight從當前窗口設置其.height()help。這看起來像:

$('#div').height(function(index, height) { 
    return window.innerHeight - $(this).offset().top; 
}); 

演示http://jsfiddle.net/d3ays/

+0

如果頁面比瀏覽器窗口,這將最終頁腳高度也設置爲0高沒有考慮到可能應用於div的任何填充。這裏是比較高度以及調整填充的代碼。 `$('#div')。height(function(index,height){var_current_height = $(this).height(); \t var new_height = window.innerHeight - $(this).offset()。 top - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom')); \t if(new_height> current_height)return new_height; }) ; ` – todd 2013-11-06 21:34:06

0

你可以試試下面的代碼,這個功能是用於獲取窗口的高度:

function GetHeight() 
{ 
    var y = 0; 
    if (self.innerHeight) 
    { 
      y = self.innerHeight; 
    } 
    else if (document.documentElement && document.documentElement.clientHeight) 
    { 
      y = document.documentElement.clientHeight; 
    } 
    else if (document.body) 
    { 
      y = document.body.clientHeight; 
    } 
    return y; 
} 

然後使用jQuery給height你DIV動態如下:

document.ready(function(){ 
    var heightOfDiv = GetHeight(); 
    jQuery('#rightRail').css("top",heightOfDiv +"px"); 
}); 

通過根據需要添加或減去像素來操作變量heightOfDiv後。

也許這適合你。

1

如果頁面比瀏覽器窗口jAndy的解決方案最終會在div高度設置爲0,它也沒有考慮到高任何可以應用於div的填充。這裏是比較高度以及調整填充的代碼。

$('#div').height(function(index, height) { 
    var current_height = $(this).height(); 
    var new_height = window.innerHeight - $(this).offset().top - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom')); 
    if (new_height > current_height) return new_height; 
});