HTML:
<div class="container">
<img src="http://placehold.it/500x500" alt="500x500" />
</div>
<div class="container">
<img src="http://placehold.it/100x500" alt="100x500" />
</div>
<div class="container">
<img src="http://placehold.it/500x100" alt="500x100" />
</div>
<div class="container">
<img src="http://placehold.it/500x800" alt="500x800" />
</div>
<div class="container">
<img src="http://placehold.it/800x500" alt="800x500" />
</div>
<div class="container">
<img src="http://placehold.it/100x100" alt="100x100" />
</div>
<div class="container">
<img src="http://placehold.it/200x100" alt="200x100" />
</div>
CSS:
div.container { width: 200px; height: 200px; line-height: 200px; overflow: hidden; border: 10px solid white; box-shadow: 0 1px 8px #BBB; margin: 10px; text-align: center; }
div.container img { position: relative; vertical-align:middle; }
div.container img.wide { max-height: 100%; }
div.container img.tall { max-width: 100%; }
div.container img.square { max-width: 100%; }
的Javascript:
$(window).load(function(){
var $imgs = $("div.container img");
$imgs.each(function(){
var cW = $(this).parent().width();
var cH = $(this).parent().height();
var w = $(this).width(); //I want the CURRENT width, not original!!
var h = $(this).height(); //I want the CURRENT height, not original!!
var dW = w - cW;
var dH = h - cH;
console.log(cW + " " + cH + " " + w + " " + h + " " + dW + " " + dH);
if (w > h){
$(this).addClass("wide");
$(this).css("left", -dW/2);
}
else if (w < h){
$(this).addClass("tall");
$(this).css("top", -dH/2);
}
else { $(this).addClass("square"); }
});
});
我正在通過ja添加vascript,一個基於它們的比例的圖像元素的類。這3個類將爲圖像設置最大寬度和最大高度css屬性,從而調整它們的大小。 之後,我需要調整大小的圖像的尺寸,但我能得到的是原始圖像的尺寸。這不好!我嘗試使用width()
,outerWidth
,naturalWidth
,每種寬度,但我只是不能正確的。
那麼,是否有一種方法可以在應用CSS規則(如max-width
和max-height
)之後獲取圖像的尺寸?最好採用一致的方式,不要使用定時器和間隔,或者類似的東西。
非常感謝!
'寬度()'確實給你目前的寬度... http://jsfiddle.net/mYZVR/ – Curt