【发布时间】:2014-03-20 10:34:55
【问题描述】:
所以我在玩纵横比以从我之前犯的一些错误中吸取教训,然后遇到了某种头痛。
在我的代码中,我的 div 的 w/h 比率基于我的 div 的高度(可以是宽度但选择的高度)但是由于宽度为 %,我的 div 的大小基于高度和它打开的窗口的宽度。
我想要做的是能够保持基于高度 % 的比率,但不让宽度因窗口大小而扭曲。
我知道这样做我不应该使用基于 % 的解决方案,但是我似乎找不到一个单位或方法可以在不搞砸 div 大小的情况下做到这一点。
关于我应该如何进行的任何想法?
这里是代码:http://jsfiddle.net/L9Srn/
<div id="container">
</div>
html,body {
width: 100%;
height: 100%;
}
#container {
background: red;
width: 26.25%;
height: 72.3%;
margin-left: auto ;
margin-right: auto ;
}
(function( $ratio ) {
$.fn.keepRatio = function(which) {
var $this = $(this);
var w = $this.width();
var h = $this.height();
var ratio = w/h;
$(window).resize(function() {
switch(which) {
case 'width':
var nh = $this.width() / ratio;
$this.css('height', nh + 'px');
break;
case 'height':
var nw = $this.height() * ratio;
$this.css('width', nw + 'px');
break;
}
});
}
})( jQuery );
$(function(){
$('#container').keepRatio('height');
});
【问题讨论】:
标签: jquery html css aspect-ratio