当background-size设置为包含时,如何获取背景图像的尺寸?

HTML:

some text

CSS:

 .logo-container { display: block; background: url(img/logo.png) no-repeat center; background-size: contain; width:100%; height:20%; } 

如何获得背景图像缩放到的当前尺寸?

我假设背景图像尺寸与.logo-container尺寸不同。

小提琴: http : //jsfiddle.net/umXk3/

由于您已经知道图像是780x150缩放格式的780x150 ,因此您可以从.logo-container的尺寸中推断出其当前尺寸:

 var width = $('.logo-container').width(); var height = $('.logo-container').height(); // Calculate dimensions depending on if width is greater than height: var imgWidth = width > height ? 780/150 * height : width; var imgHeight = height > width ? 150/780 * width : height; 

试试吧

 var wdth = $('.logo-container img').width(); var hght = $('.logo-container img').height(); 

或者你也可以得到div的高度和宽度

 var wdth = $('.logo-container').width(); 

因为图像是该div的背景图像。