2015-05-14 58 views
1

我編寫了此代碼,根據屏幕上的可用空間更改包裝盒的寬度和高度。當我打開頁面時,div加載得很好,但是當我調整它的大小時div不會改變。更改div寬度隨着負載和調整大小

var width = (($(window).width()) - 100); 
var height = (($(window).height()) - 100); 

$(window).ready(function() { 
    $("#wrapper").width(width); 
    $("#wrapper").height(height); 
}); 

$(window).resize(function(){ 
    $("#wrapper").width(width); 
    $("#wrapper").height(height); 
}); 
<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Xyz</title> 
</head> 
<body> 
    <div id="wrapper"> 
     asd 
    </div> 
</body> 
</html> 
+1

你有沒有想過在CSS中使用媒體查詢或相對單位? (VH,VW,%,em) –

+0

Flexbox也是一種選擇,但尚未得到普遍支持。 – Taplar

回答

0

您需要重新計算的尺寸。

$(window).resize(function(){ 
    width = (($(window).width())-100); 
    height = (($(window).height())-100); 
    $("#wrapper").width(width); 
    $("#wrapper").height(height); 
}); 
2

您需要將事件處理程序中重新計算heightwidth變量:

$(window).ready(calculateSize);  
$(window).resize(calculateSize); 

function calculateSize() { 
    var width = $(window).width() - 100; 
    var height = $(window).height() - 100; 
    $("#wrapper").width(width); 
    $("#wrapper").height(height); 
} 

不過請注意,這是可能的,僅CSS:

#wrapper { 
    position: absolute; 
    top: 0; 
    left: 0; 
    right: 100px; 
    bottom: 100px; 
} 
0

我用這個功能我寫了,它運行良好:

//when I load the page 
window.onload = function(event) { resizeDiv(); } 
//when I resize the page 
window.onresize = function(event) { resizeDiv(); } 

function resizeDiv() { 
    vpw = $(window).width()-100; 
    vph = $(window).height()-100; 

    $('#wrapper').css({'height': vph + 'px'}); 
    $('#wrapper').css({'width': vpw + 'px'}); 
} 
相關問題