当background-size设置为包含时,如何获取背景图像的尺寸? [英] How to get dimensions for a background image when background-size is set to contain?

查看:306
本文介绍了当background-size设置为包含时,如何获取背景图像的尺寸?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML:

<div class="logo-container">
    <span>some text</span>
</div>

CSS:

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

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

How can I get the current dimension on which the background-image was scaled to?

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

I'm assuming that the background image dimension differs from the dimension of the .logo-container.

推荐答案

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

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

Since you already know that the image is 780x150 in its unscaled format, you can deduce its current dimensions from the dimensions of .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;

这篇关于当background-size设置为包含时,如何获取背景图像的尺寸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆