1
我試圖創建一個頁面,其中居中放置的div調整大小以適合頁面水平和垂直同時保持比例。Resize Div,同時保持比例
目前我正在使用JS和CSS的組合,但我不確定它是否特別高效 - 它也似乎有點冒險。
我該如何清理這段代碼或重寫它來實現這個目標?
的Javascript
function changesize(){
var $width = $(".aspectwrapper").height();
var $changewidth = $width * 1.5;
var $doc = $(document).width();
var $height;
if ($doc <= $changewidth){ $changewidth = ($doc - 100);
$height = (($doc - 100)/1.5);
$(".aspectwrapper").css('height', "" + $height + "");
};
$(".content").css('width', "" + $changewidth + "");
$(".aspectwrapper").css('width', "" + $changewidth + "");
};
$(document).ready(function(e) {
$(changesize);
});
$(window).resize(function(e) {
$(changesize);
});
CSS
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
.aspectwrapper {
display: inline-block;
position: relative;
margin: 0 auto;
height: 90%;
border: #F00 1px solid;
background-color: #F00;
}
.content {
position: absolute;
top: 0;
bottom: 0;
right: 0;
margin-top: 60px;
outline: thin dashed green;
overflow: hidden;
background-color: #09C;
}
#wrapper {
width: 100%;
height: 100%;
text-align: center;
background-color: #0F3;
float: left;
}
HTML
<div id="wrapper">
<div class="aspectwrapper">
<div class="content"> CONTENT GOES HERE</div>
</div>
<div style="clear:both;"></div>
</div>
雖然這確實調整基於瀏覽器的大小在div,我需要保持DIV的大小相同的比率,特別是1:1.5的高寬 - 的CSS方法不保持該比值。 – RobM 2012-08-05 22:15:37
在這種情況下,我會使用jQuery來調整文檔加載的CSS。我會將div的高度發送給一個變量,並改變元素的'.css()'寬度(即'.css('width','x * 1.5');')以及元素左邊距的長度('.css('left',' - x * .75');')。 – Kwon 2012-08-06 02:08:47
漂亮的小中心式 - 即使它沒有解決問題.. – T4NK3R 2014-02-14 11:48:06