2013-05-09 105 views
0

我在我的頁面上有DIV s,其中包含IMG s。在圖像點擊時,它們在燈箱中打開,但在DIV內部,它們應該完全填充DIV,但保留寬高比。用裁剪圖像填充div,保留長寬比

這是我到目前爲止所取得的成績,問題在於圖像處於縱向模式時縱橫比不會保留。

http://jsfiddle.net/btvET/1/

所以我需要的是一個CSS的方法來垂直和水平居中圖像,而完全填充包裝DIV(當然裁剪圖像的溢流份)。

這是可能的,僅限CSS,還是需要JS?瀏覽器兼容性是IE8和Higer以及所有現代瀏覽器。

與JS/JQuery的解決它像這樣:

function resizeImages(){ 
    $("#container img").each(function() { 
     var thisHeight = $(this).height(); 
     var thisWidth = $(this).width(); 
     var containerWidth = $(this).parent().width(); 
     var containerHeight = $(this).parent().height(); 
     var diff = 0; 
     if(thisHeight > thisWidth){ 
      //portrait 
      $(this).css("width","100%"); 
      thisHeight = $(this).height(); 
      diff = thisHeight - containerHeight; 
      $(this).css("margin-top",-(diff/2)); 
     } 
     else if(thisWidth > thisHeight){ 
      //landscape 
      $(this).css("height","100%"); 
      var thisWidth = $(this).width(); 
      if(thisWidth < containerWidth){ 
       $(this).css("width", containerWidth); 
       thisWidth = containerWidth; 
      } 
      diff = thisWidth - containerWidth; 
      $(this).css("margin-left",-(diff/2)); 
     } 
     $(this).css("opacity",1); 
    }); 
} 

的設置不透明度爲1,在到底是因爲我只想完成調整時,顯示的圖像,所以我將它們設置爲不透明:在CSS中爲0,然後在調整大小後顯示它們。

這適用於我在所有容器寬度和圖像模式。

+0

您可以根據圖像的大小添加不同的類嗎?不同的水平和不同的垂直? – Lucas 2013-05-10 07:25:40

+0

@Lucas也許這是可能的,確定服務器端是哪種圖像模式...如果沒有其他方式?! – 2013-05-10 08:15:14

+0

請參閱http://php.net/manual/en/function.getimagesize.php,這可能有所幫助。然後爲圖像容器創建兩個css類,一個用於縱向,一個用於橫向。或者使用JS! :) – 2013-05-11 02:57:00

回答

3

這將需要Javascript的實施。使用jQuery,你可以檢查高度是否大於寬度,反之亦然。

你可以這樣做:

$(".container img").each(function(){ 
var thisWidth = $(this).width(); 
var thisHeight = $(this).height(); 

if(thisWidth > thisHeight) { 
    $(this).css("width", "auto"); 
    $(this).css("height", "100%"); 
} else if(thisHeight > thisWidth) { 
    $(this).css("width", "100%"); 
    $(this).css("height", "auto"); 
} 

}); 

希望這有助於。

0

這聽起來與我想做的事情類似,我想我已經設法在沒有Javascript的情況下實現它,但它需要一個虛擬的空白圖像。我有一個1920x1537的圖像,我想在其他地方將其顯示在16:9的縱橫比上,但響應速度很快。首先,我創建了一個空白的1920x720圖像。我使用GIF是因爲它的文件大小(2.1KB)在這種情況下比PNG或JPEG小得多。

HTML:

<div class="responsive-clipped mainphoto-margins"> 
    <img class="img-responsive" src="imgs/blank16x9.gif"> 
    <img class="img-responsive img-clipped" src="imgs/main9.jpg"> 
</div> 

CSS:

.responsive-clipped { 
    position: relative; 
    left: 0; 
    top: 0; 
    width: 100%; 
    margin: 0; 
    padding: 0; 
    overflow: hidden; 
} 

.img-clipped { 
    position: absolute; 
    left: 0; 
    top: -60%; 
} 

/* From Bootstrap */ 
.img-responsive { 
    display: block; 
    max-width: 100%; 
    height: auto; 
} 

我與top: -60%設置發揮,直到它的權利尋找這一形象。我不確定您是否可以實現50%的垂直居中,或者您是否需要根據高寬比進行計算。在後一種情況下,如果每幅圖像具有不同的縱橫比,那麼最好使用JavaScript解決方案。