2015-05-14 91 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'}); 
} 
相关问题