这里是 my example
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"); }
});
});
我正在通过 javascript 添加一个基于比例的图像元素类。这 3 个类将为图像设置 max-width 和 max-height css 属性,从而调整它们的大小。
之后,我需要调整后图像的尺寸,但我能得到的只是原始图像的尺寸。那可不行!我尝试使用 width()
、outerWidth
、naturalWidth
等各种宽度,但我就是无法正确使用。
那么,有没有办法在应用 max-width
和 max-height
等 CSS 规则后获取图像的尺寸?最好是一致的方式,不要使用计时器和间隔,或类似的东西。
非常感谢!
最佳答案
查看 this jsfiddle。您尝试在使用 max-height
/max-width
应用类之前获取宽度/高度,而不是在应用类之后获取。
这是测试代码(检查第二个 console.log):
$(window).load( function(){
var $imgs = $("div.container img");
$imgs.each( function(){
var cW = $(this).parent().width();
var cH = $(this).parent().height();
var w = $(this)[0].clientWidth; //I want the CURRENT width, not original!!
var h = $(this)[0].clientHeight; //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"); }
var w = $(this).width(); //I want the CURRENT width, not original!!
var h = $(this).height(); //I want the CURRENT height, not original!!
console.log( w + " " + h );
});
});
width()
, outerWidth
- 这总是返回当前宽度。
自然宽度
/naturalHeight
- 这是为了获得原始图像,例如没有应用任何样式,图像的宽度/高度(仅在较新的浏览器中适用于 IMG 标签)
关于jquery - 应用最大宽度和最大高度后获取当前图像宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13138103/