2011-11-15 122 views
20

我有一個問題等同於這張海報: Jquery problem with height() and resize()JQuery的:動力高度()的窗口大小調整()

但解決不解決我的問題。我有三個堆疊的div,我想使用JQuery使中間的高度調整到窗口高度的100%,減去其他頂部底部div的高度(23px * 2)。它適用於調整大小,但當文檔初始加載時它關閉(短)16px。

HTML

<body> 
<div id="bg1" class="bg">top</div> 
<div id="content"> 
    help me. seriously. 
</div> 
<div id="bg2" class="bg">bottom</div> 
</body> 

CSS

html, 
body { 
    width:100%; 
    height:100%; 
} 

.bg { 
width:315px; 
height:23px; 
margin:0 auto; 
text-indent:-9000px; 
} 

#bg1 {background:url(../images/bg1.png) 0 50% no-repeat;} 
#bg2 {background:url(../images/bg2.png) 0 50% no-repeat;} 

#content { 
width:450px; 
margin:0 auto; 
text-align: center; 
} 

JQuery的

$(document).ready(function(){ 
    resizeContent(); 

    $(window).resize(function() { 
     resizeContent(); 
    }); 
}); 

function resizeContent() { 
    $height = $(window).height() - 46; 
    $('body div#content').height($height); 
} 
+0

我在找這樣的東西嗎?或者頁腳是否應該隨頁面一起移動? http://www.cssplay.co.uk/layouts/basics2.html小提琴會很好! – mrtsherman

+0

我可以做那樣的事情,但我堅持使用服務器端生成的HTML。我被要求用JQuery來解決這類問題。 – Gregir

+0

什麼是9000px文字縮進? – mrtsherman

回答

50

我覺得應該有一個沒有JavaScript解決方案,但這是怎麼回事?

http://jsfiddle.net/NfmX3/2/

$(window).resize(function() { 
    $('#content').height($(window).height() - 46); 
}); 

$(window).trigger('resize'); 
+0

實際上,您可以在一行中完成。更短! – mrtsherman

+0

奇怪的是,這做到了。謝謝。 – Gregir

+0

https://jsfiddle.net/53hoq9w7/ – Pierre

0

要看到窗口的高度,同時(或之後)將被重新調整,試試吧:

$(window).resize(function() { 
$('body').prepend('<div>' + $(window).height() - 46 + '</div>'); 
}); 
6

好了,怎麼樣一個CSS的答案!我們使用display: table。然後,每個div都是行,最後我們將100%的高度應用於中間'行',並且voilà。

http://jsfiddle.net/NfmX3/3/

body { display: table; } 
div { display: table-row; } 
#content { 
    width:450px; 
    margin:0 auto; 
    text-align: center; 
    background-color: blue; 
    color: white; 
    height: 100%; 
} 
+0

男人!我知道有一個CSS唯一的解決方案!你激勵了我。夥計們,在任何JS之前,更喜歡這個非JS解決方案。它不夠乾淨,你可能需要使用一些額外的標記,但仍然值得。 –

+0

爲什麼人們認爲CSS總是比JS好? – barell

+0

@barell它並不總是更好,但是它涉及表示的地方通常最好只使用樣式,而不是實現行爲/邏輯。另外一個好處是CSS通過設計具有彈性,而JavaScript則因設計而變得脆弱。 –

3

的乾淨的解決方案 - 也純屬CSS - 將使用計算和VH。

中間div的HEIGH將正是如此計算:

#middle-div { 
height: calc(100vh - 46px); 
} 

也就是說,視口高度的100%減去2 * 23像素。 這將確保頁面正確加載並且是動態的(demo here)

還請記住使用方塊大小,所以填充和邊框不會使div填充視口。

+0

幾乎所有當前瀏覽器都支持calc(這裏是:http://caniuse.com/#feat=calc) 同樣適用於vh(這裏是:http://caniuse.com/#feat=viewport-units) –

相關問題