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

Rai*_*sen 2 html css jquery

HTML:

<div class="logo-container">
    <span>some text</span>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

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

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

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

Nic*_*ren 6

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

由于您已经知道图像是未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;
Run Code Online (Sandbox Code Playgroud)