Is it possible to use JavaScript to get the actual size (width and height in pixels) of a CSS referenced background image?
+3
A:
Yes, and I'd do it like this...
window.onload = function() {
var imageSrc = document
.getElementById('hello')
.style
.backgroundImage
.replace(/"/g, '')
.replace(/url\(|\)$/ig, '');
// 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 make a new
Image
object and set itssrc
to the new image. - We can then read the width & height.
- This method also has the advantage that we are not creating temporary DOM elements.
jQuery would probably a lot less of a headache to get going.
alex
2010-06-23 02:04:36
+1
A:
Here it is in 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.
Kirk
2010-06-23 03:01:12