获取背景图像的最终大小
is there an easy way to get the final height and width of a background image with Javascript or jQuery even if a background-size
property was applied?
有没有一种简单的方法可以使用Javascript或jQuery获取背景图像的最终高度和宽度,即使应用了background-size属性?
I mean, I know I can get the background image url and load it to an Image
object and then get the width and height. But it is the size of the source image. If someone scaled it with CSS then the size changed
我的意思是,我知道我可以获取背景图像URL并将其加载到Image对象,然后获取宽度和高度。但它是源图像的大小。如果有人用CSS缩放它,那么大小就会改变
How can I find its final size?
我怎样才能找到它的最终尺寸?
@edit
@编辑
it is different from the question marked as similar because it doesnt say how to get the size in pixels if someone changed the background-size
它与标记为类似的问题不同,因为它没有说如果有人改变了背景大小,如何获得像素的大小
2 个解决方案
#1
11
Using getComputedStyle
, I've created this script that returns the width and height of a given element's background, in pixels. It works with:
使用getComputedStyle,我创建了这个脚本,它返回给定元素背景的宽度和高度,以像素为单位。它适用于:
- Dimensions (width or height) set to
auto
, either explicitly or because no specific value was given (width and height default toauto
) - 尺寸(宽度或高度)设置为自动,显式或因为没有给出特定值(宽度和高度默认为自动)
- Dimensions set to percentage
%
- 尺寸设置为百分比%
- Dimensions set to pixels
px
- 尺寸设置为像素px
- Dimensions set to a combination of any of the previous. (i.e
width: 100px; height: auto
orwidth: auto; height: 32.4%
orheight: 100px; width: 2%
orwidth: 21.2%
) - 尺寸设置为以前任何一种的组合。 (即宽度:100px;高度:自动或宽度:自动;高度:32.4%或高度:100px;宽度:2%或宽度:21.2%)
background-size
set tocover
orcontain
- background-size设置为覆盖或包含
It works if background-size
is set with an external CSS file, inline CSS, inline header CSS or if it is not set at all (meaning width and height are auto
).
如果使用外部CSS文件,内联CSS,内联标题CSS或者根本没有设置(意味着宽度和高度为自动),则设置background-size。
Here's a JsFiddle (with cover example)
这是一个JsFiddle(有封面示例)
http://jsfiddle.net/gp4e9d3z/3/
http://jsfiddle.net/gp4e9d3z/3/
And here's StackOverflow's code snippet (with percentage auto
units)
这里是StackOverflow的代码片段(自动单位百分比)
function getBackgroundSize(elem) {
// This:
// * Gets elem computed styles:
// - CSS background-size
// - element's width and height
// * Extracts background URL
var computedStyle = getComputedStyle(elem),
image = new Image(),
src = computedStyle.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2'),
cssSize = computedStyle.backgroundSize,
elemW = parseInt(computedStyle.width.replace('px', ''), 10),
elemH = parseInt(computedStyle.height.replace('px', ''), 10),
elemDim = [elemW, elemH],
computedDim = [],
ratio;
// Load the image with the extracted URL.
// Should be in cache already.
image.src = src;
// Determine the 'ratio'
ratio = image.width > image.height ? image.width / image.height : image.height / image.width;
// Split background-size properties into array
cssSize = cssSize.split(' ');
// First property is width. It is always set to something.
computedDim[0] = cssSize[0];
// If height not set, set it to auto
computedDim[1] = cssSize.length > 1 ? cssSize[1] : 'auto';
if(cssSize[0] === 'cover') {
// Width is greater than height
if(elemDim[0] > elemDim[1]) {
// Elem's ratio greater than or equal to img ratio
if(elemDim[0] / elemDim[1] >= ratio) {
computedDim[0] = elemDim[0];
computedDim[1] = 'auto';
} else {
computedDim[0] = 'auto';
computedDim[1] = elemDim[1];
}
} else {
computedDim[0] = 'auto';
computedDim[1] = elemDim[1];
}
} else if(cssSize[0] === 'contain') {
// Width is less than height
if(elemDim[0] < elemDim[1]) {
computedDim[0] = elemDim[0];
computedDim[1] = 'auto';
} else {
// elem's ratio is greater than or equal to img ratio
if(elemDim[0] / elemDim[1] >= ratio) {
computedDim[0] = 'auto';
computedDim[1] = elemDim[1];
} else {
computedDim[1] = 'auto';
computedDim[0] = elemDim[0];
}
}
} else {
// If not 'cover' or 'contain', loop through the values
for(var i = cssSize.length; i--;) {
// Check if values are in pixels or in percentage
if (cssSize[i].indexOf('px') > -1) {
// If in pixels, just remove the 'px' to get the value
computedDim[i] = cssSize[i].replace('px', '');
} else if (cssSize[i].indexOf('%') > -1) {
// If percentage, get percentage of elem's dimension
// and assign it to the computed dimension
computedDim[i] = elemDim[i] * (cssSize[i].replace('%', '') / 100);
}
}
}
// If both values are set to auto, return image's
// original width and height
if(computedDim[0] === 'auto' && computedDim[1] === 'auto') {
computedDim[0] = image.width;
computedDim[1] = image.height;
} else {
// Depending on whether width or height is auto,
// calculate the value in pixels of auto.
// ratio in here is just getting proportions.
ratio = computedDim[0] === 'auto' ? image.height / computedDim[1] : image.width / computedDim[0];
computedDim[0] = computedDim[0] === 'auto' ? image.width / ratio : computedDim[0];
computedDim[1] = computedDim[1] === 'auto' ? image.height / ratio : computedDim[1];
}
// Finally, return an object with the width and height of the
// background image.
return {
width: computedDim[0],
height: computedDim[1]
};
}
// Stuff for debugging
function updateData() {
var background = getBackgroundSize(document.body);
document.getElementById('width').innerHTML = background.width + 'px';
document.getElementById('height').innerHTML = background.height + 'px';
document.getElementById('winWidth').innerHTML = getComputedStyle(document.body).width;
document.getElementById('winHeight').innerHTML = getComputedStyle(document.body).height;
}
// Execute onload, so that the background image is already loaded.
window.onload = window.onresize = updateData;
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
background: url('http://hdwallpapersfit.com/wp-content/uploads/2015/03/images-7.jpg');
background-size: 80% auto;
}
div {
background: rgba(0, 0, 0, 0.5);
color: #fff;
}
<div id="data">
Background width: <span id="width"></span>
<br>
Background height: <span id="height"></span>
<hr>
Body width: <span id="winWidth"></span>
<br>
Body height: <span id="winHeight"></span>
</div>
更多相关文章
- jQuery的宽度、内宽和外宽、高度、内高和外高有什么区别
- 模态的jQuery动态高度宽度
- 当侧面物品具有不同宽度时,保持中间物品居中
- HTML DIV百分比宽度奇奇怪怪的间距产生了?
- 如何在HTML主体上设置网格ExtJS,高度为100%
- 另一个div内的任意宽度的中心div
- 当给出%宽度时,表的主体减少了Head的col 1空间的总空间
- 让列在3列CSS布局中扩展到相同的高度?
- 宽度切换jQuery中的Animate在FireFox中不起作用? [重复]