2013-03-12 49 views
0

我试图做一个图像大小198px的正方形div定标与overflow:hiddenjQuery的,缩放和调整图像大小

魔术类是指img

$('.magic').on('load', function(){ 
    var self = $(this); 
    var width = self.width(); 
    var height = self.height(); 
    if(width>height){ 
     self.css('height', '198px'); 
     self.css('width', 'auto'); 
    } 
    else{ 
     self.css('width', '198px'); 
     self.css('height', 'auto'); 
    } 
}); 

现在img充盈div而不是比它大。

由于在风景照片不是完美缩放,而是拉伸。

+0

什么是'image'的大小? – 2013-03-12 15:44:18

回答

4

见琴:http://jsfiddle.net/powtac/VcLKL/19/

$(document).ready(function() { 
    $(".magic").each(function(){ 
     var self = $(this); 
     var width = self.width(); 
     var height = self.height(); 

     if(width > height){ 
      self.css('height', '198px'); 
      var ratio = width/height; 
      self.css('width', 198 * ratio); 
      self.css('margin-left', ((198 - parseInt(self.css('width')))/2)); 
     } 
     else{ 
      self.css('width', '198px'); 
      var ratio = height/width; 
      self.css('height', 198 * ratio); 
      self.css('margin-top', ((198 - parseInt(self.css('height')))/2)); 
     } 
    }); 
});