使用 JavaScript 获取 CSS 背景图像的大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3098404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the Size of a CSS Background Image Using JavaScript?
提问by Kirk Ouimet
Is it possible to use JavaScript to get the actual size (width and height in pixels) of a CSS referenced background image?
是否可以使用 JavaScript 获取 CSS 引用的背景图像的实际大小(以像素为单位的宽度和高度)?
回答by alex
Yes, and I'd do it like this...
是的,我会这样做......
window.onload = function() {
var imageSrc = document
.getElementById('hello')
.style
.backgroundImage
.replace(/url\((['"])?(.*?)\)/gi, '')
.split(',')[0];
// I just broke it up on newlines for readability
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
alert('width =' + width + ', height = ' + height)
}
Some notes...
一些笔记...
- We need to remove the
url()part that JavaScript returns to get the proper image source. We need to split on,in case the element has multiple background images. - We make a new
Imageobject and set itssrcto the new image. - We can then read the width & height.
- 我们需要删除
url()JavaScript 返回的部分以获得正确的图像源。,如果元素有多个背景图像,我们需要拆分。 - 我们创建一个新
Image对象并将其设置src为新图像。 - 然后我们可以读取宽度和高度。
jQuery would probably a lot less of a headache to get going.
jQuery 可能不会那么令人头疼。
回答by Killah
Can't comment under answers, so here is jQuery version including background-size(posted because this question is first one in google search and may be useful to someone else than me):
无法在答案下发表评论,所以这里是 jQuery 版本,包括background-size(发布是因为这个问题是谷歌搜索中的第一个问题,可能对我以外的其他人有用):
function getBackgroundSize(selector, callback) {
var img = new Image(),
// here we will place image's width and height
width, height,
// here we get the size of the background and split it to array
backgroundSize = $(selector).css('background-size').split(' ');
// checking if width was set to pixel value
if (/px/.test(backgroundSize[0])) width = parseInt(backgroundSize[0]);
// checking if width was set to percent value
if (/%/.test(backgroundSize[0])) width = $(selector).parent().width() * (parseInt(backgroundSize[0]) / 100);
// checking if height was set to pixel value
if (/px/.test(backgroundSize[1])) height = parseInt(backgroundSize[1]);
// checking if height was set to percent value
if (/%/.test(backgroundSize[1])) height = $(selector).parent().height() * (parseInt(backgroundSize[0]) / 100);
img.onload = function () {
// check if width was set earlier, if not then set it now
if (typeof width == 'undefined') width = this.width;
// do the same with height
if (typeof height == 'undefined') height = this.height;
// call the callback
callback({ width: width, height: height });
}
// extract image source from css using one, simple regex
// src should be set AFTER onload handler
img.src = $(selector).css('background-image').replace(/url\(['"]*(.*?)['"]*\)/g, '');
}
or as jQuery plugin:
或作为 jQuery 插件:
(function ($) {
// for better performance, define regexes once, before the code
var pxRegex = /px/, percentRegex = /%/, urlRegex = /url\(['"]*(.*?)['"]*\)/g;
$.fn.getBackgroundSize = function (callback) {
var img = new Image(), width, height, backgroundSize = this.css('background-size').split(' ');
if (pxRegex.test(backgroundSize[0])) width = parseInt(backgroundSize[0]);
if (percentRegex.test(backgroundSize[0])) width = this.parent().width() * (parseInt(backgroundSize[0]) / 100);
if (pxRegex.test(backgroundSize[1])) height = parseInt(backgroundSize[1]);
if (percentRegex.test(backgroundSize[1])) height = this.parent().height() * (parseInt(backgroundSize[0]) / 100);
// additional performance boost, if width and height was set just call the callback and return
if ((typeof width != 'undefined') && (typeof height != 'undefined')) {
callback({ width: width, height: height });
return this;
}
img.onload = function () {
if (typeof width == 'undefined') width = this.width;
if (typeof height == 'undefined') height = this.height;
callback({ width: width, height: height });
}
img.src = this.css('background-image').replace(urlRegex, '');
return this;
}
})(jQuery);
回答by anhh
var actualImage = new Image();
actualImage.src = $('YOUR SELECTOR HERE').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
actualImage.onload = function() {
width = this.width;
height = this.height;
}
回答by anhh
var dimension, image;
image = new Image();
image.src = {url/data}
image.onload = function() {
dimension = {
width: image.naturalWidth,
height: image.naturalHeight
};
console.log(dimension); // Actual image dimension
};
回答by Kirk Ouimet
Here it is in jQuery:
这是在 jQuery 中:
var actualImage = new Image();
actualImage.src = $('YOUR SELECTOR HERE').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
actualImage.width // The actual image width
actualImage.height // The actual image height
Thanks for the sweet regex alex.
感谢甜蜜的正则表达式亚历克斯。

