这是我的示例:链接
HTML:
我正在通过JavaScript为图像元素添加一个类,基于它们的比例。这3个类将设置图像的max-width和max-height CSS属性,从而调整它们的大小。 之后,我需要调整大小后的图像尺寸,但是我只能得到原始图像的尺寸。那不太好!我尝试使用width()、outerWidth、naturalWidth等各种宽度,但我就是无法正确获取它。
所以,有没有一种方法可以在应用了像max-width和max-height这样的CSS规则之后获取图像的尺寸?最好是一种一致的方法,而不是使用定时器和间隔,或类似的东西。
非常感谢!
<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"); }
});
});
我正在通过JavaScript为图像元素添加一个类,基于它们的比例。这3个类将设置图像的max-width和max-height CSS属性,从而调整它们的大小。 之后,我需要调整大小后的图像尺寸,但是我只能得到原始图像的尺寸。那不太好!我尝试使用width()、outerWidth、naturalWidth等各种宽度,但我就是无法正确获取它。
所以,有没有一种方法可以在应用了像max-width和max-height这样的CSS规则之后获取图像的尺寸?最好是一种一致的方法,而不是使用定时器和间隔,或类似的东西。
非常感谢!
width()
函数会返回当前元素的宽度... http://jsfiddle.net/mYZVR/ - Curtis