2012-01-09 139 views
0

我希望图像是窗口宽度的100%减去标题的高度及其边距。 在同一时间,它不应该比窗口的宽度更宽。这一点,我想我已经用下面的代码实现:使用jQuery调整高度或宽度以百分比减去值并保持高宽比

HTML:

<header></header> 

<img id="photo" src="http://farm5.staticflickr.com/4031/4718599034_5ab720d0f9_b.jpg" realwidth="1024" realheight="768" /> 

CSS:

header { 
    position:absolute; 
    top:0px; 
    left:0px; 
    width:300px; 
    height:150px; 
    background-color:#000; 
    margin:20px; 
} 

img { 
    position:absolute; 
    bottom:10px; 
    left:0px; 
    max-width:1024px; 
    max-height:768px; 
    margin-right:20px; 
    margin-left:20px; 

} 

而且,jQuery的:

function setSize() { 
    var windowHeight = $(window).height(); 
    var headerHeight = $('header').height(); 
    var windowWidth = $(window).width(); 


    $('img').height(windowHeight - headerHeight - 40); 

    $('img').width(windowWidth - 40); 
} 


    $(window).resize(function() { 
setSize(); 
setRatio(); 
    }); 

setSize(); 

Here's the JSFiddle.

我可以不做,我想要做的是保持图像的纵横比。这可以怎么做?

回答

1

如果更改图像的NATIVE高度属性而不是CSS高度,宽度将自动跟随宽高比。

$('img').attr('height',(windowHeight - headerHeight - 40)+'px'); 
+0

感谢您的建议。虽然这在一个方面起作用,但似乎并不适用于两者。也就是说,宽度会跟随高度,但高度也不会跟随宽度。 – bravokiloecho 2012-01-09 15:23:08

相关问题