2011-08-26 30 views
1

需要jquery图像调整大小,如果图像宽度> 400然后使用调整大小宽度:50%,像100X100小尺寸的其他图像不需要调整大小。图像调整与jquery

我使用此代码

var max_size = 400; 
$(".comment p.message a.fancy img").each(function(i) { 
    if ($(this).height() > $(this).width()) { 
    var h = max_size; 
    var w = Math.ceil($(this).width()/$(this).height() * max_size); 
    } else { 
    var w = max_size; 
    var h = Math.ceil($(this).height()/$(this).width() * max_size); 
    } 
    $(this).css({ height: h, width: w }); 
}); 

但这个代码不检查更小的图像。

+1

我不知道这是否是解决方案,但将对象传递给.css()的正确表示法是$(this).css({'height':h,'width':w}) ;' – m90

+1

@ m90:'{height:h,width:w}'很好。 –

+0

@mu太短:昨天有完全相同的问题,而没有使用引号为我抛出一个错误? – m90

回答

0

尝试这种情况:http://jsfiddle.net/aJffu/2/

var maxsize = 400; 

$("#images img").each(function() { 
    var t = $(this); 
    var maxdim = Math.max(t.width(), t.height()); 
    if (maxdim > maxsize) { 
     t.css({ 
      width: t.width()/2, 
      height: t.height()/2 
     }); 
    } 
}); 

这半部的图像的大小,如果宽度或高度超过maxsize。不应该很难适应您的具体需求。例如,this version会缩放图像,使其最长尺寸为maxsize