2013-02-23 68 views
1

HTML調整所有圖像在一個div

<div class="test"><img src="1.jpg"><img src="2.jpg"><img src="3.jpg"></div> 
<div class="test"><img src="4.jpg"></div> 

的jQuery

var max = 100; 
var img = $('div.test img'); 
if (img.width() > max) { 
    img.width = max; 
} 

我想<div>.test類中找到的所有圖像被重新調整爲規定的最大寬度。

回答

8

像這樣:

var max = 100; 
$('div.test img').each(function() { 
    if ($(this).width() > max) { 
     $(this).width(max); 
    } 
}); 

...通過所有的圖像,檢測和將循環(可能)設置每個的寬度依次。

替代解決方案:

var max = 100; 
$('div.test img').width(function(i,w) { 
    return Math.min(w, max); 
}); 

進一步閱讀:

2

就這麼簡單:

$('div.test img').css({'max-width' : '100px'}); 
+0

我想ü可以寫爲'CSS({'最大寬度':'100%'});' – 2013-02-23 04:42:28