Is it possible to use JavaScript to get the actual size (width and height in pixels) of a CSS referenced background image?
Yes, and I'd do it like this...
window.onload = function () { var imageSrc = document .getElementById('hello') .style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2') .split(',')[0]; // I just broke it up on newlines for readability var image = new Image(); image.src = imageSrc; image.onload = function () { var width = image.width, height = image.height; alert('width =' + width + ', height = ' + height); }; };
Some notes...
url()
part that JavaScript returns to get the proper image source. We need to split on ,
in case the element has multiple background images.Image
object and set its src
to the new image.jQuery would probably a lot less of a headache to get going.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With