Obtain background image width
is possible to get background image width which is defined in CSS?
body {
background-image: url('background.jpg');
}
I need something like开发者_运维百科 this:
window.getComputedStyle(document.body, 'background-width');
var u = window.getComputedStyle(document.body, 'background-image');
u = u.replace(/url\(/, '').replace(/\)/, '');
var w = 0;
var i = new Image();
i.onload = function( ){ w = this.width; alert(w); }
i.src = u;
warning: i have ommitted a case, when body has no background image specified, keep that in mind.
is possible to get background image width which is defined in CSS?
I don't think so, but you should be able to use a little trick : Load the image into an img
element as described in this question.
If you do this after the document has been fully loaded, the browser should fetch the image from the cache.
It's impossible to do this directly without some sort of work around.
- Use JQuery to detect what image the background has, with the imagesLoaded (recommended) or onImagesLoad plugin.
- Use the JQuery Dimensions plugin to get the image size.
精彩评论