2012-01-09 140 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

相關問題