2013-06-13 38 views

回答

5

我已經創建fiddle,有助於實現這一結果。

但是,如果div.frame的寬度大於其圖像的寬度,則會導致圖像的分辨率大於其分辨率。

假設下面的HTML

<div class="frame"> 
    <img src="http://stuffpoint.com/parrots/image/240658-parrots-white-parrot.jpg" /> 
</div> 

這將具有以下樣式施加

.frame { 
    width: 100%; 
    height: 200px; 
    overflow: hidden; 
    position: relative; 
} 

.frame img { 
    width: 100%; 
} 

強制性jQuery來垂直居中上負載的圖象並調整

$(function(){ 
    centerImageVertically(); 
    $(window).resize(function() { 
     centerImageVertically(); 
    }); 
    function centerImageVertically() { 
     var imgframes = $('.frame img'); 
     imgframes.each(function(i){ 
      var imgVRelativeOffset = ($(this).height() - $(this).parent().height())/2; 
      $(this).css({ 
       'position': 'absolute', 
       'top': imgVRelativeOffset * -1 
      }); 
     }); 
    } 
}); 

UPDATE : st的替代方式破解上面的JavaScript:

$(function() { 
     var centerImageVertically = function() { 
      var imgframes = $('.frame img'); 
      imgframes.each(function (i) { 
       var imgVRelativeOffset = ($(this).height() - $(this).parent().height())/2; 
       $(this).css({ 
        'position': 'absolute', 
        'top': imgVRelativeOffset * -1 
       }); 
      }); 
     }; 

     centerImageVertically(); 
     $(window).resize(centerImageVertically); 
    }); 
+1

很好的答案..幫了我很多。 – Paul