Is it possible to use JavaScript to get the actual size (width and height in pixels) of a CSS referenced background image?
Advertisement
Answer
Yes, and I’d do it like this…
JavaScript
x
18
18
1
window.onload = function () {
2
var imageSrc = document
3
.getElementById('hello')
4
.style.backgroundImage.replace(/url((['"])?(.*?)1)/gi, '$2')
5
.split(',')[0];
6
7
// I just broke it up on newlines for readability
8
9
var image = new Image();
10
image.src = imageSrc;
11
12
image.onload = function () {
13
var width = image.width,
14
height = image.height;
15
alert('width =' + width + ', height = ' + height);
16
};
17
};
18
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
Image
object and set itssrc
to the new image. - We can then read the width & height.
jQuery would probably a lot less of a headache to get going.